I have been teaching myself JS and Jquery primarily for GM scripts (im not a programmer by day) and tried to come up with a solution to append a DIV to another DIV for every single listing on autotrader.com. They are siblings under multiple parents. The full code is here http://userscripts.org/scripts/review/83865 and working.
I came up with this:
var counter=0;
$('.dealer-info').ea开发者_开发技巧ch(function(){
$(this).appendTo($('.car-info')[counter]);
counter=counter+1;
});
Is there a more elegant way to do this?
Any advice would be appreciated as i want my code to be simpler.
Regards, anthony
.each()
provides the index as the first variable to the callback function, so you can do this:
$('.dealer-info').each(function(i) {
$('.car-info').eq(i).append(this);
});
Since .appendTo()
just gets flipped around to .append()
internally it's less wasteful and a bit easier on the eyes to do it this way using .eq()
to get the item at that index.
To be more performant, you should keep a reference to .car-info
outside the loop, like this:
var cars = $('.car-info');
$('.dealer-info').each(function(i) {
cars.eq(i).append(this);
});
So you want to append each element with class "dealer-info" to each element with the class "car-info"?
Does $(".dealer-info").appendTo($(".car-info"));
not do this?
Along the lines of your code, but a little bit more jQuery way. Haven't tried this, but should work fine.
$('.dealer-info').each(function(index, value){
$(this).appendTo($('.car-info').eq(index));
});
精彩评论