jQuery UI -多个自动完成-不一致的结果

jQuery UI - Multiple autocomplete - inconsistent results

本文关键字:不一致 结果 UI jQuery      更新时间:2023-09-26

我有以下tags.json文件:

     [
        {"label" : "Aragorn"},
        {"label" : "Arwen"},
        {"label" : "Bilbo Baggins"},
        {"label" : "Boromir"}
     ]

和下面的javascript代码(与工作演示相同):

  <script>
  $(function() {
    function split( val ) {
      return val.split( /,'s*/ );
    }
    function extractLast( term ) {
      return split( term ).pop();
    }
    $( "#people" )               //DIFF FROM DEMO
      // don't navigate away from the field on tab when selecting an item
      .bind( "keydown", function( event ) {
        if ( event.keyCode === $.ui.keyCode.TAB &&
            $( this ).data( "ui-autocomplete" ).menu.active ) {
          event.preventDefault();
        }
      })
      .autocomplete({
        source: function( request, response ) {
          $.getJSON( 'tags.json', {                           //DIFF FROM DEMO
            term: extractLast( request.term )
          }, response );
        },
        search: function() {
          // custom minLength
          var term = extractLast( this.value );
          if ( term.length < 2 ) {
            return false;
          }
        },
        focus: function() {
          // prevent value inserted on focus
          return false;
        },
        select: function( event, ui ) {
          var terms = split( this.value );
          // remove the current input
          terms.pop();
          // add the selected item
          terms.push( ui.item.value );
          // add placeholder to get the comma-and-space at the end
          terms.push( "" );
          this.value = terms.join( ", " );
          return false;
        }
      });
  });
  </script>

但是当我在输入框中输入例如:"ar"时,我得到Aragorn, Arwen, Bilbo BagginsBoromir。我不明白为什么BilboBoromir在结果中?我应该只得到AragornArwen,因为这些字符串包含'ar'字符串…

问题在于,在jQuery示例中,$.getJSON()函数调用一些服务器端脚本,该脚本使用术语参数做一些事情,即过滤名称。在您的示例中,将按原样返回tags.json文件,其中包括所有结果。如果你想根据某些东西过滤结果,例如输入的术语,你需要在调用response(这是当前$.getJSON()函数的回调)之前应用该过滤。