2011-02-28 51 views
2

这段代码如何不能如其下面所写的那样工作,但如果我将function testBgChange(){注释掉,并将代码保留在该函数内,它就可以正常工作。如果我将代码保存在函数中然后调用该函数,它会有什么不同?仅在函数外部工作的JavaScript代码 - 为什么?

<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> 

回答

7

因为var redvar white,在函数内部声明时,只能从函数内访问。这是一个问题,因为setTimeout将在全局范围内调用eval,该范围无法访问这些变量。

有很多方法可以解决这个问题,但最好给setTimeout一个函数而不是字符串。

var red = "#FF00000"; 
setTimeout(function() { 
    changeBgColor(red); 
}, time); 
+0

感谢:作为新的函数创建一个封闭保留访问变量中包含函数这将解决您的问题!本想不出=) – mdc 2011-02-28 09:24:58