开发者

how to using "For" instead of "each" function in jquery

Today i'm very stack with a Work and jQ. I was get a morning for it but i can't resolve it :(. My Work here:

<div class="container">
    <p class="test">a</p>
    <div>
        <p class="test">a</p>
    </div>
</div>

In norm开发者_运维知识库al, i can using jQ with each function for select all <p class="test">a</p> EX:

$(".test").each(function() {
    $(this).text('a');
});

But i hear everyone talk that, for function get a less timeload than each function. Now i want using for instead of each.. but i don't know how to write code jQ in this case.

Somebody can help me!. thankyou!


I wouldn't worry about it unless you were iterating through hundreds of them.

for loop is usually used with normal DOM (aka without jQuery) traversing, like...

var elements = document.getElementById('something').getElementsByTagName('a');

var elementsLength = elements.length;

for (var i = 0; i < elementsLength; i++) {

    elements[i].style.color = 'red';
}

Caching of elementsLength is a good idea so it is not calculated every iteration. Thanks to CMS for this suggestion in the comments.

Just adapt that for your jQuery object if you wanted to do it with jQuery.

Replace elements variable with your jQuery collection, like $('#something a'). I think you may need to rewrap the object if you need to do any more jQuery stuff with it.


One thing to watch out for is that using an ordinal accessor on the result of a jQuery selection will return a native DomElement. If you want to use jQuery methods on them, you have to re-wrap them:

var testElements = $('.test');

for (var i = 0; i < testElements.length; i++) {
  // Using $() to re-wrap the element.
  $(testElements[i]).text('a');
}

I'd second what others have said though. Unless you're dealing with many elements, this is premature optimization. Re-wrapping the elements to use the .text() method may even bring it back to no gain at all.


have you tried the obvious solution?

var nodes = $(".test");
for(var i = 0; i < nodes.length; i++)
{
    var node = nodes[i];
}


This article shows that each() has no significant performance penalty until you get into the hundreds of thousands of looped-over items.


Another alternative:

for (var i = 0; i < $('.test').length; i++){
    var element = $('.test').eq(i);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜