如果for循环中的语句被忽略

时间:2014-08-05 21:27:30

标签: javascript

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

1 个答案:

答案 0 :(得分:8)

显然它不会进入if,因为cssVal不是string,而是CSSStyleRule对象。你应该这样做:

cssVal = sheet.cssRules[i];

然后在if

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

然后,改变颜色:

cssVal.style.backgroundColor = "blue";