javascript - JQuery 自动完成建议未排序

标签 javascript jquery autocomplete

<分区>

我在使用 JQuery UI 对自动完成结果进行排序时遇到问题。 enter image description here

从上图中,当用户决定搜索大蒜并开始输入“g”时,它应该首先显示“大蒜”而不是鸡蛋。

查看我的代码。 ingredient.txt 中的成分按字母顺序排序,所以我认为这就是问题所在..

我该怎么做

$(function() {
    jQuery.get('ingredients.txt', function(data) {
        var availableTags = data.split(', ');   
        availableTags = availableTags.sort();           
        //console.log("The available Tag are "+ availableTags);
        function split( val ) {
            return val.split(",");
        }
        function extractLast( term ) {
            return split( term ).pop().sort();
        }   
        // don't navigate away from the field on tab when selecting an item                  
        $( "#tags" ).bind( "keydown", function( event ) {
            if ( event.keyCode === $.ui.keyCode.TAB && $( this ).autocomplete( "instance" ).menu.active ) {
                event.preventDefault();
            }
        }).autocomplete({
            minLength: 0,
            source: function( request, response ) {
              // delegate back to autocomplete, but extract the last term
              response( $.ui.autocomplete.filter(
                availableTags, extractLast( request.term ) ) );
            },
            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
                // var projectDiv = '<div class="projectBody" id="selectedItems">'+ ui.item.value +'</div>';
                terms.push( ui.item.value );                                  
                for(var i = 0; i < terms.length; i++) {
                    var elements = terms[i];                        
                }
                // add placeholder to get the comma-and-space at the end
                terms.push( "" );
                //$("#tags").val().wrap( "<div class='new'>nn</div>" );
                this.value = terms.join( "," );                               
                return false;
            }
        });
    });
});

最佳答案

经过仔细研究,这就是我想出的。

<script type="text/javascript">

                    $(function() {
                        jQuery.get('ingredients.txt', function(data) {
                        var availableTags = data.split(', ');   
                        availableTags = availableTags.sort();           
                        //console.log("The available Tag are "+ availableTags);
                        function split( val ) {
                          return val.split(", ");
                        }
                        function extractLast( term ) {
                          return split( term ).pop();
                        }                        
                        $( "#tags" )
                          // don't navigate away from the field on tab when selecting an item
                          .bind( "keydown", function( event ) {
                            if ( event.keyCode === $.ui.keyCode.TAB &&
                                $( this ).autocomplete( "instance" ).menu.active ) {
                              event.preventDefault();
                            }
                          })
                          .autocomplete({
                            minLength: 0,
                            source: function( request, response ) {
                              var term = $.ui.autocomplete.escapeRegex(extractLast(request.term))
                                    // Create two regular expressions, one to find suggestions starting with the user's input:
                                    , startsWithMatcher = new RegExp("^" + term, "i")
                                    , startsWith = $.grep(availableTags, function(value) {
                                        return startsWithMatcher.test(value.label || value.value || value);
                                    })
                                    // ... And another to find suggestions that just contain the user's input:
                                    , containsMatcher = new RegExp(term, "i")
                                    , contains = $.grep(availableTags, function (value) {
                                        return $.inArray(value, startsWith) < 0 &&
                                            containsMatcher.test(value.label || value.value || value);
                                    });            

                                // Supply the widget with an array containing the suggestions that start with the user's input,
                                // followed by those that just contain the user's input.
                                response(startsWith.concat(contains));
                            },
                            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
                             // var projectDiv = '<div class="projectBody" id="selectedItems">'+ ui.item.value +'</div>';
                              terms.push( ui.item.value );                                
                              for(var i = 0; i < terms.length; i++)
                                {
                                    var elements = terms[i];                        
                                }
                              console.log('<div class="projectBody" id="selectedItems">'+ ui.item.value +'</div>');
                              $("#selectedItems").css("backgroundColor", "blue");                         
                              // add placeholder to get the comma-and-space at the end
                              terms.push( "" );                           
                              this.value = terms.join( "," );                                 
                              return false;
                            }
                          });
                      });
                });

                </script>

关于javascript - JQuery 自动完成建议未排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33754943/

相关文章:

javascript - 为什么带有 json 内容类型的 ajax post 发送数据 url 编码?

javascript - JQuery AJAX 加载使用 AJAX 的表单

javascript - 此代码在 pc 浏览器上运行良好,但在移动设备上不起作用

javascript - jqGrid EditRow ErroFunc 回调用法

ruby-on-rails - 如何在 jQuery.ui.autocomplete 中的自动完成弹出窗口下方添加所有搜索的链接?

autocomplete - 如何使 SublimeText 版本 4 的自动完成功能像版本 3 一样?

java - 如何将自动完成文本字段分配给 JTable 单元格?

javascript - 在 Angularjs 中访问对象

javascript - 当鼠标未移动到动态元素上时,鼠标悬停不起作用

javascript - JQUERY:Div slider 有时显示 2 个 div