【发布时间】:2013-10-28 14:07:36
【问题描述】:
我混合使用 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>
有什么办法可以加快速度吗?我真的很喜欢这个功能,如果可能的话,我想把它保留在网站上。
【问题讨论】:
-
您想要进行 5000 次搜索有什么具体原因吗?我的第一个想法是将其减少到更小的数量。
-
您的目标浏览器是什么?您可以通过不使用 jQuery 来加快速度,而在每个使用 jQuery 的地方。不过,这可能是微不足道的。
-
如果你想在这样的体积场景中提高速度,首先摆脱 jQuery,然后跳过 RegExp 构造函数并使用 regexp 文字代替。如果您仍然考虑在变量中使用 jquery 缓存 $(this)。像 $this = $(this);
标签: javascript jquery search