开发者

jquery for loop thru div

开发者 https://www.devze.com 2023-02-21 20:38 出处:网络
would like to use a loop to express this .. $(\"div:nth-child(3)\").css({\"left\": \"5px\"}); $(\"div:nth-child(2)\").css({\"left\": \"215px\"});

would like to use a loop to express this ..

$("div:nth-child(3)").css({"left": "5px"});
$("div:nth-child(2)").css({"left": "215px"});
$("div:nth-child(1)").css({"left": "425px"});

how can each be referenced...

var x=0;
$("div").each(function(){
   x=x+100;
   $(this).css('position','absolute'); 
   $(this).css({"left": "xpx"});  // not sure about this li开发者_如何转开发ne
  });


var x=0;
$("div").each(function(){
   x = x + 100;
   $(this).css({'position':'absolute', 'left': x + 'px'});
});


This is probably what you want

$(this).css({"left": x+"px"});


You can write

$(this).css("left", x);

You don't need to add px; jQuery will add it automatically.

If you do want to explicitly add a unit, you can use string concatenation:

$(this).css("left", x + "px");


var xx=0;
$("div").each(function(){
    xx+=100;
    $(this).css('position','absolute'); 
    $(this).css({"left": xx+"px"}); 
});

Try not to use 'x' as a variableName, might be confusing in later stadia. Fixed your code.

0

精彩评论

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