简体   繁体   English

将属性保存到变量并将 append 保存到 DOM 元素

[英]Save property to variable and append it to DOM element

The code bellow does not work, obviously objects can't be saved to variables in that manner!下面的代码不起作用,显然对象不能以这种方式保存到变量中!

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;
    }

Would somebody show me the right way?有人会告诉我正确的方法吗? 10x and BR, Stephan 10x 和 BR,斯蒂芬

You need to use bracket notation and strings:您需要使用括号表示法和字符串:

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;
    }
}

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

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