开发者

Looking for better/elegant solution to appendTo DIVs with jquery in listings

开发者 https://www.devze.com 2023-01-12 03:59 出处:网络
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 autotrad

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));
});
0

精彩评论

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