2013-04-17 113 views
0

查询代表对象名称当您看到以下示例时,事情就会很清楚。通过函数参数

function AddStyle(prob, value) { 
    Elem = document.getElementById('box'); 
    Elem.style.prob = value; 
} 

// Here is, when usage. 
AddStyle('backgroundColor', 'red'); 

正如你在前面的例子中所看到的,我们有两个参数(prob是属性名称),(value是属性的值)。

该示例不起作用,没有错误也会出现。 我敢肯定,这一行Elem.style.prob = value;,特别是这里的问题style.prob

回答

0

变量没有以这种方式解决。基本上,您的代码正在寻找字面上称为prob的样式属性。您必须使用方括号来访问该属性,因为对象是通过属性名称进行索引的。喜欢的东西:

Elem.style[prob] = value; // Access the property of style equal to the value of prob 

这将相当于:

Elem.style['backgroundColor'] = value; 

这将等同于:

Elem.style.backgroundColor = value; 

Demo