我必须迭代一组具有<li>s的<ul>,并根据输入的单词对其进行过滤。基于id的第一个代码运行良好。但问题是我们有重复的is,这破坏了过滤器。因此,我为class分配了is,并进行了类选择,现在它工作得很好,但有一些问题。主要问题是类选择过滤器比Id选择过滤器慢。因为它是一个很大的列表,所以在使用类名进行迭代时,我可能会遇到速度慢的问题。有没有办法让它更快些?另外,我想知道为什么类的选择会更慢!
下面是我基于id进行迭代的代码:
$.each(propertiesList, function () {
var item = $("#" + this.id).parent();
if(this.property.toLowerCase().indexOf(value.toLowerCase()) === -1) {
item.addClass('no-match');
}
else {
item.parents('.root-property-category').show().addClass('expanded').children('ul').show();
item.removeClass('no-match');
}
});以下是基于类的迭代:
$.each(propertiesList, function () {
var item = $("#available-properties [class*='" + this.id + "']").parent();
if(this.property.toLowerCase().indexOf(value.toLowerCase()) === -1) {
console.log(item)
item.addClass('no-match');
}
else {
console.log(item)
item.parents('.root-property-category').show().addClass('expanded').children('ul').show();
item.removeClass('no-match');
}
});发布于 2013-06-10 13:08:55
大家好,谢谢你的帮助..
最后,我用下面的方法修复了这个问题,希望这能对某些人有所帮助。
$.each(propertiesList, function () {
var item = $('[id="'+ this.id+'"]').parent();
if(this.property.toLowerCase().indexOf(value.toLowerCase()) === -1) {
item.addClass('no-match');
}
else {
item.parents('.root-property-category').show().addClass('expanded').children('ul').show();
item.removeClass('no-match');
}
});此$('[id="'+ this.id+'"]')选择所有具有id的元素,并且运行速度很快。
发布于 2013-06-07 19:58:43
使用class selector而不是attribute contains selector可以大大提高性能
var item = $("#available-properties ." + this.id).parent();发布于 2013-06-07 20:03:07
试试这个:
var item = $("#available-properties").find("." + this.id).parent();翻译成人类应该是:找到id为available-properties的元素,然后找到类为this.id的子类,然后找到子类的父类。
而
$("#available-properties [class*='" + this.id + "']")说明:找到属性类为this.id的elemens,找到其中一个是id为available-properties的元素的子元素。效率要低得多。
https://stackoverflow.com/questions/16983451
复制相似问题