我正在使用这个 JS 代码制作横幅:
var images = ["../../images/g11.jpg","../../images/g9.jpg","../../images/g10.jpg"];
var titulos = ["title1","title2","title3"];
var resumos = ["ddd","aaa","bbb"];
var noticias = ["190","204","200"];
var total = 3;
var indice = 0;
function rotate() {
document.getElementById('imageb').src = images[indice];
document.getElementById('titulob').innerHTML = titulos[indice];
document.getElementById('resumob').innerHTML = resumos[indice];
document.getElementById('noticiab').value = noticias[indice];
indice++;
if (indice > total - 1) indice = 0;
}
function banner() {
rotate();
setTimeout(banner, 5000);
}
它按预期工作,但在一些循环后它卡住了浏览器。很确定我没有正确使用 setTimeout。有什么想法吗?
编辑:
到目前为止的工作:
function rotate(indice) {
document.getElementById('imageb').src = images[indice];
document.getElementById('titulob').innerHTML = titulos[indice];
document.getElementById('resumob').innerHTML = resumos[indice];
document.getElementById('noticiab').value = noticias[indice];
}
function banner(indice) {
var f1 = function() { banner(indice); };
var total = 3;
rotate(indice);
indice++;
if (indice > total - 1) indice = 0;
setTimeout(f1, 5000);
}
最佳答案
我将其作为 CW 发布,因为这完全是猜测。
完全 FWIW,这是我如何最小化更改该代码:Live Copy | Live Source
(function() {
var entries = [
{
img: "../../images/g11.jpg",
titulo: "title1",
resumo: "ddd",
noticia: "190"
},
{
img: "../../images/g9.jpg",
titulo: "title2",
resumo: "aaa",
noticia: "204"
},
{
img: "../../images/g10.jpg",
titulo: "title3",
resumo: "bbb",
noticia: "200"
}
];
var indice = 0;
function rotate() {
var entry = entries[indice];
document.getElementById('imageb').src = entry.img;
document.getElementById('titulob').innerHTML = entry.titulo;
document.getElementById('resumob').innerHTML = entry.resumo;
document.getElementById('noticiab').value = entry.noticia;
indice = (indice + 1) % data.length;
}
function banner() {
rotate();
setTimeout(banner, 5000);
}
banner();
})();
变化:
将所有内容放在作用域函数中以避免创建全局变量。
使用对象数组而不是并行数组。
使用数组的长度而不是单独的
total
变量。使用余数技巧获得
indice
变量的环绕。我在末尾添加了对
<banner();
的调用以启动操作,但我假设您已经调用了它,只是没有显示它。
但是,除了一些奇怪的全局变量冲突的可能性之外,我没有看到任何你的代码不应该按原样工作的原因。
关于Javascript 函数工作了一段时间,然后卡住了浏览器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20844932/