for循环中的If语句被忽略

If statement in a for loop being ignored

本文关键字:语句 If 循环 for      更新时间:2023-09-26

我有一个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";