jQuery UI使用计数机制自动完成类别

前端之家收集整理的这篇文章主要介绍了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 andeRSSon",category: "People" },{ label: "andreas andeRSSon",{ 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 andeRSSon","andreas andeRSSon",/*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/

原文链接:https://www.f2er.com/jquery/177338.html

猜你在找的jQuery相关文章