简体   繁体   English

通过功能参数查询代表对象名称

[英]inquiry about represent the object name by the function parameter

Things will be clear when you see the following example. 当您看到以下示例时,一切都会变得清楚。

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

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

As you see in the previous example, we have two parameters ( prob is the property Name), ( value is the value of property). 如上例所示,我们有两个参数( prob是属性Name),( value是属性的值)。

That example doesn't work, There are no errors Occur also. 该示例不起作用,也没有错误发生。 I'm certain that the problem in this line Elem.style.prob = value; 我确定这一行中的问题Elem.style.prob = value; and especially here style.prob . 特别是style.prob

Variables aren't resolved in that way. 变量不是以这种方式解析的。 Basically, you're code is looking for a property of style literally called prob . 基本上,您在代码中寻找的是字面意义上的样式属性prob You'll have to access the property using brackets, since objects are indexed by property name. 您必须使用方括号来访问属性,因为对象是通过属性名称索引的。 Something like: 就像是:

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

This would be equivalent to: 这等效于:

Elem.style['backgroundColor'] = value;

Which would be equivalent to: 相当于:

Elem.style.backgroundColor = value;

Demo 演示版

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM