简体   繁体   中英

Using jQuery selectors to iterate through DOM elements

Can someone tell me why this won't work?

var top = 0;
for (divToPosition in $('.positionableDiv')) {
   divToPosition.css('top',top+'px');
   top = top + 30;
}

The first reason would be the misuse of the for loop.

jQuery has an idiom for looping over selected elements..

var top = 0;
$('.positionableDiv').each(function() {
   $(this).css('top',top+'px');
   top = top + 30;
});

Please take a look at for...in for a better understanding of the way a for...in loop works in javascript, it does not enumerate in the same way as say .NET or Java.

From Article:

Although it may be tempting to use this as a way to iterate over an Array, this is a bad idea.

The correct way to iterate over a set of matched elements is with .each , as other answers have mentioned. Attempting to use a for..in loop will iterate over the properties of the jQuery object, not the elements it matched.

To improve slightly on some of the other .each examples, you could omit the top variable to clean things up a little. The first parameter to .each is in the index of the element within the set of matched elements; you could achieve the same thing by multiplying it by 30 at each step. There is no incrementing and no top variable cluttering things up:

$('.positionableDiv').each(function(i) {
    $(this).css('top', (i * 30) + "px");
});

This would work:

var top = 0;
for (var pdiv in $('.positionableDiv').get()) {
   $(pdiv).css('top', top + 'px');
   top = top + 30;
}

Basically, you use get() to retrieve the array of elements.

The "for (var key in obj)" is suitable for iterating the members of an object. It works for native JavaScript arrays as long as their prototype is not extended. A jQuery object may look as a native JavaScript array but it is not hence "for ( in )" fails.

You can use .each to iterate over a jQuery object: var top = 0;

$('.positionableDiv').each(function() {
     $(this).css('top', top);
     top += 30;
});

The $('.positionableDiv') in your statement is a jQuery object with a great many properties. What you want is to iterate through the matched elements which is not done that way.

Try:

var top = 0;
$('.positionableDiv').css('top', function(index, value) {
    var cTop = top;
    top = top + 30;
    return cTop + 'px';
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM