Error while trying to set style with JavaScript
var d = document;
div = d.body.appendChild(d.createEle开发者_如何学编程ment("DIV"));
div.id = "hi";
div.innerHTML = "Hello World";
cssStyle = ["fontFamily", "fontStyle"];
cssAn = ["Arial", "italic"];
div.style.cssStyle[0] = cssAn[0];
It does not set the style. Instead it returns an error stating "Cannot set property 0 of undefined". What could I have done wrong?
I think you want:
div.style[cssStyle[0]] = cssAn[0];
cssStyle
is not a property of div.style.
You want:
div.style[cssStyle[0]] = cssAn[0];
This is not Javascript related — it's a general programming principle.
You have a variable cssStyle
that contains "fontFamily"
and "fontStyle"
.
Accessing the property cssStyle
of div.style
is in no way related to the variable cssStyle
.
You need to div.style[cssStyle[0]] = cssAn[0]
.
EDIT:
Additionally, if you want all properties whose names are in cssStyles
and corresponding values in cssAn
to be set on div
, then, assuming cssStyle
and cssAn
have the same number of elements, you can:
for (var i = 0; i < cssStyle.length; i += 1) {
var name = cssStyle[i];
var value = cssAn[i];
div.style[name] = value;
}
精彩评论