admin管理员组

文章数量:1410737

I need to choose a property to animate and then, do animation.

The code should be like a following:

var prop = "background-color";
switch( val )
{
   case 1: prop = "color";
   case 2: prop = "border-color";
   // ...
}
item.animate( {prop: "#00FF00"}, 1000 );

JavaScript plains about using "prop" variable.

When i just say

item.animate( {"color": "#00FF00"}, 1000 );

everything is fine.

I think, a constant is expected as object property declaration.

How can i determine it at runtime ?

I need to choose a property to animate and then, do animation.

The code should be like a following:

var prop = "background-color";
switch( val )
{
   case 1: prop = "color";
   case 2: prop = "border-color";
   // ...
}
item.animate( {prop: "#00FF00"}, 1000 );

JavaScript plains about using "prop" variable.

When i just say

item.animate( {"color": "#00FF00"}, 1000 );

everything is fine.

I think, a constant is expected as object property declaration.

How can i determine it at runtime ?

Share Improve this question edited Jun 8, 2011 at 1:54 Billy ONeal 107k61 gold badges329 silver badges563 bronze badges asked Nov 2, 2010 at 9:11 AntonALAntonAL 17.4k21 gold badges84 silver badges118 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

These are equivalent:

// prop is a literal string here,
// not a variable
{prop: "#00FF00"}

and

{"prop": "#00FF00"}

you probably need to do something like this:

var obj = {};
obj[prop]="#0000ff";
item.animate( obj, 1000 );

Yes, you're correct, JavaScript expects an identifier as the property name in an object literal. You'll have to create an object and assign the property using square bracket notation.

var opts = {};
opts[prop] = "#00FF00";
item.animate(opts, 1000);

本文标签: javascriptUse string variable as object fieldsStack Overflow