开发者

Why does this JavaScript code fail to add style to text?

开发者 https://www.devze.com 2023-02-26 22:22 出处:网络
var css = [\"font-family\"]; var a = document.getElementById(\"t\"); for (var i = 0; i < a.length; i++) {
var css = ["font-family"];

var a = document.getElementById("t");

for (var i = 0; i < a.length; i++) {
    a.style[css] = ["Arial"];
}

<div id="t">He开发者_如何学编程llo World</div>

It doesn't add any font to it.


Because the for loop is never run. a.length will give undefined as a is not an array but a DOM element. i < undefined will always evaluate to false.

And as @Box9 mentioned, don't put "font-family" and "Arial" in arrays. Pass the strings directly:

var css = "font-family";
var a = document.getElementById("t");
a.style[css] = "Arial";

or

document.getElementById("t").style[css] = "Arial";

As you can also see in the function name, Element is singular, not plural.


In addition to Felix's answer, your style assignment doesn't make sense. You want something like:

a.style.fontFamily = "Arial";
0

精彩评论

暂无评论...
验证码 换一张
取 消