我混合使用 jquery 和 javascript 来搜索一堆项目。准确地说是5000+。我在网站上使用实时搜索功能,根据关键字过滤这些项目。但由于有太多的项目需要搜索,所以我想加快这个过程。
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/JavaScript">
$(document).ready(function() {
$("#filter").keyup(function() {
// Retrieve the input field text and reset the count to zero
var filter = $(this).val(), count = 0;
// Loop through the list
$(".inventory tr").each(function() {
// If the list item does not contain the text phrase fade it out
if ($(this).text().search(new RegExp(filter, "i")) < 0) {
$(this).fadeOut();
// Show the list item if the phrase matches and increase the count by 1
} else {
$(this).show();
count++;
}
});
// Update the count
var numberItems = count;
$("#filter-count").text("Number of items = "+count);
});
});
</script>
<form id="live-search" action="" class="styled" method="post">
<fieldset>
<input type="text" class="text-input" id="filter" value="" />
<span id="filter-count"></span>
</fieldset>
</form>
<div class="inventory">
<table> Stuff </table>
</div>
我能做些什么来加快速度吗?我真的很喜欢这个功能,如果可能的话,希望将其保留在网站上。
最佳答案
jQuery 比普通 JS 慢;它的好处是跨浏览器 支持,但对于循环之类的事情不需要它 对象
您正在循环内创建相同的正则表达式模式 每次迭代;外部声明一次
在内存中保存表的副本并在那里进行搜索会比每次都遍历 DOM 更快。也就是说,将数据保存在多维数组中并对其进行扫描;然后更新表格 View
已经有一个名为 dataTables 的 jQuery 插件可以为您执行此操作。
关于javascript - 如何加快大型库存文件的 javascript/jquery 速度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19636940/