指示html对象的各种属性

时间:2017-08-14 08:45:54

标签: javascript html

我要设置html对象的属性。

var property1 = 'style.visibility';
var property2 = 'style.display';
var property3 = 'style';

我尝试过以下事情。

第一

1;  object[property1] = 'visible';
2;  object[property2] = 'block';
3;  object[property3].display = 'none';

第二

1;  object.property1 = 'visible';
2;  object.property2 = 'block';
3;  object.property3.display = 'none'; 

在我的情况下,只有first;3;运作良好 有没有办法轻松指出html对象的属性?

1 个答案:

答案 0 :(得分:1)

您可以使用reduce()创建函数来访问嵌套属性。

var property1 = 'style.visibility';
var property2 = 'style.display';
var property3 = 'style';

var obj = {style: {visibility: 1, display: 2}}

function getProp(prop, obj) {
  return prop.split('.').reduce(function(r, e) {
    return r[e]
  }, obj)
}

console.log(getProp(property1, obj))
console.log(getProp(property2, obj))
console.log(getProp(property3, obj))