gpt4 book ai didi

javascript 代码只能在函数之外工作——为什么?

转载 作者:行者123 更新时间:2023-12-03 16:32:53 26 4
gpt4 key购买 nike

为什么这段代码不能像下面写的那样工作,但如果我注释掉 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>

最佳答案

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

有多种方法可以解决这个问题,但最好给 setTimeout 一个函数而不是一个字符串。这将解决您的问题,因为新函数创建了一个闭包,它保留对包含函数中的变量的访问:

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

关于javascript 代码只能在函数之外工作——为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5139999/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com