2

我有一个大约 200 个项目的列表(在表格行中):

<tr><td><h5>Title</h5></td>
    <td class="nazwa">some text</td>
    <td>Some additional stuff</td>
</tr>

我创建了一个 jQuery 函数,如果它们与搜索的字符串匹配,它会过滤(显示或隐藏)项目

jQuery.fn.filterItems = function(str){
    var title = jQuery(this).find("h5").text().toLowerCase();
    var name = jQuery(this).find(".nazwa").text().toLowerCase();
    if( title.search( str ) < 0 && name.search( str ) < 0 ){
        jQuery(this).hide().removeClass("visible");
    }
    else{
        jQuery(this).show().addClass("visible");
    }
    return this;
}

每次用户在搜索输入中输入内容时,它都会自动过滤项目并显示与输入匹配的项目:

jQuery("#search_items").on("input", function(){
        var s = jQuery(this).val();
        if(s != ""){
           jQuery('.list-of-items tr').each(function(){
               jQuery(this).filterItems( s.toLowerCase() );
           });
        }
        else{
            jQuery('.list-of-items tr').show().addClass("visible");
        }
    });

这在 PC 上运行良好,但在移动设备上存在一些性能问题。有时输入和过滤器反应之间有相当长的延迟。

如何在性能/资源使用方面优化此实时搜索?

4

1 回答 1

0

这可能会有所帮助:https ://davidwalsh.name/javascript-debounce-function 。

// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
function debounce(func, wait, immediate) {
    var timeout;
    return function() {
        var context = this, args = arguments;
        var later = function() {
            timeout = null;
            if (!immediate) func.apply(context, args);
        };
        var callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
    };
};

您必须从上面包装事件函数(在您的情况下inputdebounce()

只需阅读有关去抖动和节流的更多信息

如果你有一个使用 Angular 的项目,它会更容易和更快:https ://docs.angularjs.org/api/ng/filter/filter 。

于 2016-01-22T16:44:27.720 回答