用for替换jQuery

问题描述 投票:10回答:2

我一直在使用$ .each进行迭代一段时间,但我一直听到有人说使用原生JS来做循环。我非常关心性能,但我不确定是否总能以有意义的方式替换$ .each。

所以我的问题是,是否有可能总是用$替换$ .each,如果不是,那么什么时候可以做到以及什么时候做不到的经验。

我有一个这样的人:

 $this.find("div.class").each(function (){
  var $thisparent = $(this).parent();

  if (condition) {          
   $(this).prepend($thisparent.text());
  }

  if (condition2) {          
   $(this).prepend($thisparent.text());
  }

 });
javascript jquery for-loop each
2个回答
9
投票

这就是jQuery对.each所做的,基本上:

$.fn.each = function(callback) {
    var i, length = this.length;
    for(i = 0; i < length; ++i) {
        callback.call(this[i]);
    }
};

因此,用callback.call调用替换你的匿名函数的'内容'并不难。请务必使用jQuery对象替换this

转换您提供的代码:

var foo = $this.find("div.class"),
    fooLength = foo.length,
    i,
    $thisparent;

for (i = 0; i < fooLength; ++i) {
    $thisparent = $(foo[i]).parent();

    if (condition) {          
        $(foo[i]).prepend($thisparent.text());
    }

    if (condition2) {          
        $(foo[i]).prepend($thisparent.text());
    }
}

对于额外(潜在)速度,将foo[i]缓存到临时。也是,只在需要时指定$thisparent。如果conditioncondition2相互排斥,请使用单个if (condition || condition2)


© www.soinside.com 2019 - 2024. All rights reserved.