我班上有以下方法:
/**
* Loops through a JSON object and assigns the styles to the element
*/
this._assignClass = (function (className, element) {
for (var styleName in className) {
if (className.hasOwnProperty(styleName)) {
var style = element.style;
// *** THIS LINE IS NOT CORRECT ***
style.styleName = className[styleName];
}
}
});
以及以下JSON对象:
this.configuration = {
class: {
arrowUp: {
width: "0px",
height: "0px",
borderLeft: "10px solid transparent",
borderRight: "10px solid transparent",
borderBottom: "10px solid black"
}
}
};
我正在调用这样的方法:
this._assignClass(this.configuration.class.arrowUp, someDivElement);
该方法应该采用JSON对象并将所有样式分配给该对象中的元素this.configuration.class.arrowUp
。我遇到的问题是style.styleName
被错误地解释了。如何将正确的值传递给style
?
答案 0 :(得分:3)
this._assignClass = (function (className, element) {
for (var styleName in className) {
if (className.hasOwnProperty(styleName)) {
var style = element.style;
// *** TRY THIS ONE ***
style[styleName] = className[styleName];
}
}
});
答案 1 :(得分:1)
样式只是一个对象,因此您可以使用[]
分配其属性。
this._assignClass = (function (className, element) {
for (var styleName in className) {
if (className.hasOwnProperty(styleName)) {
//simply this would work
element.style[styleName] = className[styleName];
}
}
});