为什么这段代码不能像下面所写的那样工作,但如果我注释掉function testBgChange(){
并将代码保留在该函数中,它就能正常工作。如果我将代码保留在函数中然后调用该函数会有什么不同呢?
<html>
<head>
<script type="text/javascript">
testBgChange();
function testBgChange(){
var i = 0;
var c = 0;
var time = 3000;
var incr = 3000;
while(i<=3){
if(c==0){
var red = "#FF0000";
setTimeout("changeBgColor(red)",time);
time+=incr;
c=1;
}
else if(c==1){
var white = "#FFFFFF";
setTimeout("changeBgColor(white)",time);
time+=incr;
c=0;
}
i+=1;
}
}
function changeBgColor(color){
document.getElementById("alert").style.backgroundColor = color;
}
</script>
</head>
<body>
<p id="alert">
<br>
<br>
Testing
<br>
<br>
</p>
</body>
</html>
答案 0 :(得分:7)
因为var red
和var white
在函数内部声明时,只能在函数内访问。这是一个问题,因为setTimeout
将在全局范围内调用eval
,而该范围无法访问这些变量。
有很多方法可以解决这个问题,但最好是给setTimeout
一个函数而不是一个字符串。这将解决您的问题,因为新函数创建了一个闭包,它保留了对包含函数中变量的访问权限:
var red = "#FF00000";
setTimeout(function () {
changeBgColor(red);
}, time);