2011-05-30 66 views
1

下面的代碼不起作用,顯然對象不能以這種方式保存到變量!將屬性保存到變量並將其追加到DOM元素

function styleElement(aNode){ 
    var cssProperty; var cssValue; 
    for(var c=0; c<2; c++){  
     cssProperty = c ? backgroundColor : color; 
     cssValue = c ? 'blue' : '#fff'; 
     aNode.style.cssProperty = cssValue; 
    } 

有人會告訴我正確的方法嗎? 10倍和BR,斯蒂芬

回答

4

您需要使用bracket notation和字符串:

function styleElement(aNode){ 
    var cssProperty; var cssValue; 
    for(var c=0; c<2; c++){  
     cssProperty = c ? "backgroundColor" : "color"; 
     cssValue = c ? 'blue' : '#fff'; 
     aNode.style[cssProperty] = cssValue; 
    } 
} 
+0

哦,一模一樣... – wong2 2011-05-30 12:36:41

+4

我會刪除我的.. – wong2 2011-05-30 12:37:06

+1

坦克爲你的快速回復:) – kidwon 2011-05-30 13:17:45

相關問題