jQuery   发布时间:2022-03-30  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了jQuery UI使用计数机制自动完成类别大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在基于文档中的类别示例实现jQuery UI自动完成.我想将结果数添加到Categories标题中,因此不显示“Products”而是显示“Products(3)”.我知道_renderMenu函数需要从示例中修改,但我无法理解如何修改它.任何帮助我开始正确的道路将非常感激.

以下是jQuery UI Autocomplete Categories演示的示例代码

<script>
    $.widget( "custom.catcomplete",$.ui.autocomplete,{
        _renderMenu: function( ul,items ) {
            var self = this,currentCategory = "";
            $.each( items,function( index,item ) {
                if ( item.category != currentCategory ) {
                    ul.append( "<li class='ui-autocomplete-category'>" + item.category + "</li>" );
                    currentCategory = item.category;
                }
                self._renderItem( ul,item );
            });
        }
    });
    </script>
    <script>
    $(function() {
        var data = [
            { label: "anders",category: "" },{ label: "andreas",{ label: "antal",{ label: "Annhhx10",category: "Products" },{ label: "Annk K12",{ label: "Annttop C13",{ label: "anders ande@L_489_9@on",category: "People" },{ label: "andreas ande@L_489_9@on",{ label: "andreas johnson",category: "People" }
        ];

        $( "#search" ).catcomplete({
            delay: 0,source: data
        });
    });
    </script>



<div class="demo">
    <label for="search">Search: </label>
    <input id="search" />
</div>

解决方法

一个好的策略是创建一个对象/哈希,它将类别存储为键,并将与该类别匹配的项目数组存储为值.换句话说,你想构建这样的东西:
{ "Products": ["Annhhx10","Annk K12",/*etc*/],"People": ["anders ande@L_489_9@on","andreas ande@L_489_9@on",/*etc*/]
}

构建完成后,您可以遍历它并输出每个类别,然后输出其值.这样做的好处就是你要做的就是获取项目的数量是采取与当前类别对应的数组的长度.就像是:

$.widget("custom.catcomplete",{
    _renderMenu: function(ul,items) {
        var self = this,categories = { };

        /* Build a Dictionary/hash where keys are categories and values are 
         * arrays of items with that category 
         */
        $.each(items,function (index,item) {
            if (!categories.hasOwnProperty(item.category)) {
                 categories[item.category] = [item];
            } else {
                categories[item.category].push(item);
            }
        });

        /* Iterate over the hash we just built and display a category followed by its
         * items.
         */
        $.each(categories,function(category,items) {
            if (category) {
                ul.append("<li class='ui-autocomplete-category'>" + category + " (" + items.length + ")</li>");
            }
            $.each(items,item) {
                self._renderItem(ul,item);
            });
        });
    }
});

例:http://jsfiddle.net/andrewwhitaker/vNtGd/

大佬总结

以上是大佬教程为你收集整理的jQuery UI使用计数机制自动完成类别全部内容,希望文章能够帮你解决jQuery UI使用计数机制自动完成类别所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。