我一直在使用$ .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());
}
});
这就是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
。如果condition
和condition2
相互排斥,请使用单个if (condition || condition2)
。
有人比较了for
和$.each
的表现:
http://jquery-howto.blogspot.com/2009/06/javascript-for-loop-vs-jquery-each.html