开发者

jQuery Each() as a For statement?

开发者 https://www.devze.com 2023-03-28 13:22 出处:网络
I have a jQuery.each() function that I would like to turn into a FOR statement. I was wondering how I can turn

I have a jQuery.each() function that I would like to turn into a FOR statement.

I was wondering how I can turn

     jQuery('.myclass').each(function() {
       //do stuff
     }

int开发者_如何学Co a

   for ( var i=0; i<.myclass.length; i++) {
    //do stuff
   }

?


jQuery objects are array-like. They have a length property and they support accessing elements by using numeric indexes with []. So you just index directly into the resulting object:

var myclass = jQuery('.myclass');

for ( var i=0; i<myclass.length; i++) {
    // use myclass[i] here
}

This information isn't especially flagged up in the API docs, but you can find it in the documentation of the get function. The bracket notation largely replaces use of the get function except for its handling of negative index values (which are used to index relative to the end of the collection; negative indexes are only supported via get, not via []).


You can use .get() to get a standard JavaScript array. And then use a for loop in the normal way.

var nodes = $(...).get(),
    nodes_len = nodes.length;

for(var i=0; i < nodes_len; i++) {
   var node = nodes[i];

   ...
}

Or, if you just need the index number, use the following:

$(...).each(function (index) {
   ... 
});
0

精彩评论

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

关注公众号