所以我写了一个简单的程序,应该在 3 秒后更改给定网站的背景。
现在这是我的 JavaScript 代码:
//this function changes the backgrounds after 3 seconds and increments n
function changebackgroundTimed(startvariable)
{
var n = startvariable;
var loop = 1;
while (loop == 1)
{
setTimeout(function(){changebackground(n)}, 3000)
n++;
if (n == 5)
{
n=1;
}
}
}
//this function changes the background depending on the given number
function changebackground(number)
{
if (number == 1)
{
$("body").css("background","no-repeat center/120%url('../images/1.jpg')");
}
else if (number == 2)
{
$("body").css("background","no-repeat center/120%url('../images/2.jpg')");
}
else if (number == 3)
{
$("body").css("background","no-repeat center/120%url('../images/3.jpg')");
}
else if (number == 4)
{
$("body").css("background","no-repeat center/120%url('../images/4.jpg')");
}
else {
$("body").css("background","no-repeat center/120%url('../images/1.jpg')");
}
}
在 html 中我只是调用它:changebackgroundTimed(2);
问题是:当我启动页面时,它会加载很长时间,然后最终崩溃,什么也不显示。它必须与这两个功能做一些事情。你们中有人注意到我可能遗漏了什么错误吗?
最佳答案
看起来您没有更新“循环”变量,这导致它进入无限循环。
不使用 while 循环,而是使用 setInterval() 方法。这应该为您完成工作。
将变量 n 保留在函数外部,并使用外部 this 关键字引用它。
function abc(){
var self = this;
self.n = 1;
setInterval(function () {
if(self.n ===1){
self.n = self.n + 1;
// your code
}else if(){
// and so on
}
changebackground(self.n);
},3000);
}
关于javascript - 写了两个 JavaScript 函数,但其中一个似乎让我的网站崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59684591/