2017-08-14 37 views
1

我將設置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

您可以使用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))

+0

謝謝'reduce'將是我的編程大力支持。 –