简体   繁体   English

自动完成仅匹配单词开头

[英]Autocomplete is matching word starting only

This code is about Autocomplete with an external JSON array.此代码是关于使用外部 JSON 数组自动完成的。 My problem is that the autocomplete only displays when I entered the first two initial words.我的问题是自动完成仅在我输入前两个初始单词时显示。 For example, I want to find the capital "Kabul", I have to enter "Ka" to find the capital in the autocomplete.例如,我想找到大写字母“Kabul”,我必须在自动完成中输入“Ka”才能找到大写字母。 If I enter "ab" or " bu", it won't show "Kabul".如果我输入“ab”或“bu”,则不会显示“Kabul”。 Please help me.请帮我。

$(function() {
  $("#answer").autocomplete({
    minLength: 2,
    source: function(request, response) {
      var display = [];
      $.each(array, function(k, v) {
        if (v.capital.toLowerCase().indexOf(request.term.toLowerCase()) == 0) {
          display.push({ "label": v.capital });
          return;
        }
      });
      response(display);
    },

The issue is because indexOf will return the zero-based index of the occurrence of the string you're looking for, or -1 if it's not found.问题是因为indexOf将返回您要查找的字符串出现的从零开始的索引,如果未找到,则返回-1 Therefore your use of == 0 in the if condition will only hit when the search string is found at the start of the source.因此,您在if条件中使用== 0只会在搜索字符串在源的开头找到时命中。

To amend this behaviour change the condition to !== -1 ,:要修改此行为,请将条件更改为!== -1 ,:

if (v.capital.toLowerCase().indexOf(request.term.toLowerCase()) !== 1) {

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM