自定义jQuery过滤器需要优化 [英] Custom jQuery filter needs optimization
本文介绍了自定义jQuery过滤器需要优化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
< div class ='block' >
< span class ='title'>一些名称< / span>
< img src ='some.img'/>
< / div>
我试图用下面的代码对它们进行过滤。它可以工作,但速度非常慢,有时会使浏览器崩溃。
friendBlocks = friendform.find('。block');
filterFriends = function(text){
friendBlocks.each(function(){
var block;
lock = $(this);
if(block.children ('.title')。text()。toLowerCase()。indexOf(text)> = 0){
block.show();
} else {
block.hide );
}
});
};
有没有一些方法可以优化这个并更有效地进行搜索? b
解决方案
不要在每个项目上实时操作!克隆包含块div的节点,执行操作,然后替换原来的DOM。
类似于(未经测试,仅举例):
friendform = $('#container')。clone();
friendBlocks = friendform.find('。block');
filterFriends = function(text){
friendBlocks.each(function(){
var block;
lock = $(this);
if(block.children ('.title')。text()。toLowerCase()。indexOf(text)> = 0){
block.show();
} else {
block.hide );
}
});
};
$('#container')。replaceWith(friendform);
In the code below, friendBlocks has 800+ items that look like this:
<div class='block'>
<span class='title'>Some Name</span>
<img src='some.img' />
</div>
And I'm trying to filter them with the below code. It works, but is extremely slow and sometimes crashes the browser.
friendBlocks = friendform.find('.block');
filterFriends = function(text) {
friendBlocks.each(function() {
var block;
block = $(this);
if (block.children('.title').text().toLowerCase().indexOf(text) >= 0) {
block.show();
} else {
block.hide();
}
});
};
Is there some way to optimize this and do the search more efficiently?
解决方案
Do not apply the manipulation on each item in real-time! Clone the node, that contains the block divs, perform the operation, and then replace the original DOM.
Something like (not tested, just example):
friendform = $('#container').clone();
friendBlocks = friendform.find('.block');
filterFriends = function(text) {
friendBlocks.each(function() {
var block;
block = $(this);
if (block.children('.title').text().toLowerCase().indexOf(text) >= 0) {
block.show();
} else {
block.hide();
}
});
};
$('#container').replaceWith(friendform);
这篇关于自定义jQuery过滤器需要优化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文