将字符串值传递到 animate Jquery 函数时出现问题
嘿我想知道这两个代码有什么区别?第一个有效,但第二个不行?
First >>
for (i=0; i<$sequencingArray.length; i++){
...
$($sequencingArray[i]).delay(i*100).animate({'margin-left':$masterWidth});
...
}
Second >>
$propToAnimate = 'margin-left';
for (i=0; i<$sequencingArray.length; i++){
...
$($sequencingArray[i]).delay(i*100).animate({$propToAnimate:$masterWidth});
...
}
Hey I'm wonder what's the difference between these 2 codes? The first works but the 2nd doesnt?
First >>
for (i=0; i<$sequencingArray.length; i++){
...
$($sequencingArray[i]).delay(i*100).animate({'margin-left':$masterWidth});
...
}
Second >>
$propToAnimate = 'margin-left';
for (i=0; i<$sequencingArray.length; i++){
...
$($sequencingArray[i]).delay(i*100).animate({$propToAnimate:$masterWidth});
...
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是一个有效的解决方案......
“您不能在对象文字中使用变量作为属性名称。” 从这里
This is a working solution...
"You cannot use a variable as a property name inside an object literal." from here
当您使用
{'margin-left':$masterWidth}
或{$propToAnimate:$masterWidth}
时,您正在创建一个对象。因此,当我们使用 对象初始化程序< /a> ({k0:v0, k1:v1}
) 语法。最重要的是,对于您的情况
var a = {prop:20}
和var a = {'prop':20}
都会做完全相同的事情 - 创建一个对象有一个名为prop
的属性。如果您已经在其他地方说过var prop = ' different'
也没关系,prop
在{prop:20 中使用时仅被视为文字名称}
并且不被评估。要使代码的第二个版本正常工作,您可以使用对象的
a['prop']
语法。所以类似:然后你将有 obj['margin-left'] == masterWidth 。您可以在 animate 函数中使用这个对象...
animate(obj);
我希望我没有太困惑!
When you are using
{'margin-left':$masterWidth}
or{$propToAnimate:$masterWidth}
you are creating an object. So we need to know what we are doing when we create an object using the Object Initializer ({k0:v0, k1:v1}
) syntax.Most importantly for your case
var a = {prop:20}
andvar a = {'prop':20}
will both do exactly the same thing -- create an object with one property calledprop
. It doesn't matter if you had already saidvar prop = 'different'
elsewhere,prop
is just treated as a literal name when used in{prop:20}
and is not evaluated.What you could do to make the second version of your code work, is make use of the
a['prop']
syntax for objects. So something like:Then you will have
obj['margin-left'] == masterWidth
. And you can use this object in the animate function...animate(obj);
I hope I haven't been too confusing!