jQuery UI使用不同的输入自动完成


jQuery UI autocomplete with different inputs

我想为不同的输入添加不同的自动补全。例如,我有以下两个输入字段:

<input type="text" id="firstname" name="firstname" placeholder="Max" required />
<input type="text" id="lastname" name="lastname" placeholder="Mustermann" required />

因此,我目前添加了以下不同的自动完成:

$( document ).ready(function() {
    $( '#firstname' ).autocomplete({
        source: 'autocomplete_firstname.php',
        minLength: 1
    });
    $( '#lastname' ).autocomplete({
        source: 'autocomplete_lastname.php',
        minLength: 1
    });
});

这对我来说很好,但也许有比参数更好的方法吗?所以我只能在自动完成字段上使用一个类,而只能使用一个返回相同结果的.php文件?

试试这个:

$( document ).ready(function() {
var focused_inp;
    $( '#firstname,#lastname' ).on('focus',function(){ focused_inp = $(this).prop('name');}).autocomplete({
        source: function(req, res){
      $.ajax({
      url: "autocomplete.php",
      dataType: "jsonp",
      data: {action: focused_inp, data: request.term  },
      success: function(result) { res(result)  }
    }) },
        minLength: 1,
    });
});

如果您想将自动完成实例化代码与输入标记解耦,可以将自动完成源设置为数据属性。

<input type="text" data-source="foo.php"/>
<input type="text" data-source="bar.php"/>

然后,在create事件中,可以查找此属性并将其设置为源。这段代码现在适用于许多地方,因为在创建小部件时不必直接传递源选项:

$('input').autocomplete({
    minLength: 1,
    create: function() {
        var $this = $(this),
            source = $this.data('source');
        if (source) {
            $this.autocomplete('option', 'source', source);
        }
    }
});
$('input').first().autocomplete('option', 'source');
// → 'foo.php'
$('input').last().autocomplete('option', 'source');
// → 'bar.php'