for循环中的if语句将被忽略

卡马雷里尼·维伯格(Camarellini Viberg)

我有一个for循环,其中嵌套有一个if语句,但是该循环忽略了该语句并继续运行。任何想法为什么会这样?非常感谢。

JavaScript:

var sheet = document.styleSheets[0];
var cssVal = '';

function changeColor() { 
    for (i = 0; i < sheet.cssRules.length; i++) {
        cssVal = sheet.cssRules[i];
        console.log(cssVal); // Successfully outputs #box to the console.
            if (cssVal == "#box") { // Does nothing, continues iterating.
                console.log("If has run.");
                cssVal.style.backgroundColor="blue";
                break;
            }
    }
}

changeColor();

CSS:

@charset "utf-8";


#box {
    width:20px;
    height:20px;
}

#car {
    width:20px;
    height:20px;
}

HTML:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Boxes</title>
<link href="Boxes.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="box"></div>
<div id="car"></div>
<script type="text/javascript" src="Boxes.js"></script>
</body>
</html>
马可·博内利

显然,它不在内if,这是因为cssVal不是string,而是CSSStyleRule对象。您应该改为这样做:

cssVal = sheet.cssRules[i];

然后在您的if

if (cssVal.selectorText == '#box')

然后,更改颜色:

cssVal.style.backgroundColor = "blue"; 

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章