2011-04-04 112 views
0

想用一个循环来表达这个..jQuery的for循环通格

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

如何在每个被引用...

var x=0; 
$("div").each(function(){ 
    x=x+100; 
    $(this).css('position','absolute'); 
    $(this).css({"left": "xpx"}); // not sure about this line 
    }); 

回答

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

danke它的工作原理!超!谢谢 – windsurf88 2011-04-04 22:37:59

0

这可能是你想要

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

是的,:是的,谢谢! – windsurf88 2011-04-04 22:39:00

+0

你对书籍或网站学习jQuery有什么建议吗? – windsurf88 2011-04-04 23:29:30

0

您可以编写

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

您不需要添加px; jQuery会自动添加它。

如果你想明确地添加一个单元,您可以使用字符串连接:

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

尝试过,但需要: – windsurf88 2011-04-04 22:38:39

+0

错误。你不需要':'(只要你不使用大括号来创建对象字面量) – SLaks 2011-04-05 00:01:44

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

尽量不要用“X”作为VARIABLENAME,可能会在以后的场馆混乱。修正了你的代码。

+0

'xx'如何比'x'更好的变量名? – 2011-04-04 22:18:17

+0

编程时使用'x'作为变量名经常让我困惑。这不是一个错误的变量名,但我不喜欢使用它。 – rsplak 2011-04-04 22:29:25

+0

非常感谢您的建议〜! – windsurf88 2011-04-04 22:39:43