Jquery自动完成 - 搜索值并显示标签

时间:2016-07-05 10:21:42

标签: jquery autocomplete jquery-ui-autocomplete

我在手机的标签/价值清单上使用jquery自动完成功能:

[ { label: "Samsung Galaxy S7", value: "Samsung Galaxy S7"}, 
  { label: "Samsung Galaxy S6", value: "Samsung Galaxy S6"},
.....
]

我想在没有指定系列名称的情况下进行研究,即如果用户输入"三星S7"自动完成建议"三星Galaxy S7"

我尝试修改源代码如下:

[ { label: "Samsung Galaxy S7 Samsung S7", value: "Samsung Galaxy S7"}, 
  { label: "Samsung Galaxy S6 Samsung S6", value: "Samsung Galaxy S6"},
.....
]

此代码有效,但很难看,因为自动完成菜单显示"三星Galaxy S6三星S6"而不是简单的"三星Galaxy S6"

在菜单中显示另一个属性时,有没有办法对属性进行研究?

1 个答案:

答案 0 :(得分:2)

您需要使用source选项编写自定义搜索逻辑。对于一个简单的用例,类似下面的内容就可以了。有关详细信息,请参阅jQuery UI Autocomplete widget search configuration

也许您需要一个复杂的正则表达式来处理边缘情况(如果您有一个静态/信任有价值的数据源,则不需要)。



$(document).ready(function() {

  var devices = [{
    label: "Samsung Galaxy S7",
    value: "Samsung Galaxy S7"
  }, {
    label: "Samsung Galaxy S6",
    value: "Samsung Galaxy S6"
  }];

  $("#devices").autocomplete({
    source: function(req, responseFn) {
      var words = req.term.split(' ');
      var results = $.grep(devices, function(device, index) {
        var sentence = device.label.toLowerCase();
        return words.every(function(word) {
          return sentence.indexOf(word.toLowerCase()) >= 0;
        });
      });
      responseFn(results);
    }
  });

});

input {
  margin-top: 100px;
}

<link href="https://code.jquery.com/ui/1.8.23/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js"></script>
<input type="text" id="devices" />
&#13;
&#13;
&#13;