0

我必须迭代一组<ul><li>s 并根据输入的单词对其进行过滤。基于 id 的第一个代码运行良好。但问题是我们有重复的 ID,这破坏了过滤器。因此,我为班级分配了 ID 并进行了班级选择,现在它运行良好,但存在一些问题。主要问题是类选择过滤器比 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');
        }
      });
4

4 回答 4

2

使用类选择器而不是属性包含选择器可以大大提高性能

var item = $("#available-properties ." + this.id).parent();
于 2013-06-07T11:58:43.340 回答
1

尝试这个:

var item = $("#available-properties").find("." + this.id).parent();

翻译成人类它会是:找到id为available-properties的元素,然后找到class为this.id的子元素,然后找到子元素的父元素。

尽管

$("#available-properties [class*='" + this.id + "']")

说:找到属性类this.id的元素,找到那些是id为available-properties的元素的子元素。效率低得多。

于 2013-06-07T12:03:07.100 回答
1

问题是您如何按班级查找。您正在使用 : [class*='" + this.id + "']",它将查找属性class等于的所有元素this.id。我认为使用它会更快'.' + this.id,因为这是按类查找元素的正确方法。这应该比按属性查找元素要快得多。

var item = $("#available-properties ." + this.id).parent();

顺便说一句,如果您正在寻找速度增加,请eachfor循环替换您的功能。这往往要快得多。

于 2013-06-07T12:03:09.167 回答
0

大家好,感谢您的所有帮助..

最后,我通过以下方式解决了这个问题,希望这对某些人有所帮助..

  $.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-10T05:08:54.787 回答