我有大约 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 上运行良好,但在移动设备上遇到一些性能问题。有时输入和过滤器 react 之间存在相当大的延迟。
如何在性能/资源使用方面优化此实时搜索?
最佳答案
这可能会有所帮助: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);
};
};
您必须使用上面的 debounce()
包装事件函数(在您的情况下为 input
)。
只需阅读有关 debounce and throttle 的更多信息
如果你有一个使用 Angular 的项目,它会更容易、更快:https://docs.angularjs.org/api/ng/filter/filter 。
关于jQuery 过滤器优化(移动设备上性能缓慢),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34949474/