我试图在执行后重复调用JavaScript函数。
function startSlide(){
var products = [
['images/product_images/footwear/footwear_1.jpeg'],
['images/product_images/mobile/mobile_1.jpeg'],
['images/product_images/camera/camera_1.jpeg'],
['images/product_images/fashion/fashion_1.jpeg'],
['images/product_images/laptop/laptop_1.jpeg'],
['images/product_images/furniture/furniture_1.jpeg']
];
for (var i = 0; i < products.length; i++) {
var image = products[i][0];
imgslider(image, i * 800);
}
};
function imgslider(image, timeout)
{
window.setTimeout(function() {
document.getElementById('imgslider').innerHTML = "";
var product = document.getElementById('imgslider');
var elem = document.createElement("img");
product.appendChild(elem);
elem.src = image;
},timeout);
startSlide();
}
startSlide()
函数迭代数组并从数组中获取值并调用函数imgslider()
。 imgslider()
函数将图像附加到div。
在imgslider()的末尾我试图调用startSlide()以便它可以继续执行....但它无法正常工作。我怎么能这样做?
答案 0 :(得分:1)
问题是您的代码正在创建无限递归...
维护代码结构可以添加标志来解决问题
function startSlide() {
var products = [
['//placehold.it/64X64&text=1'],
['//placehold.it/64X64&text=2'],
['//placehold.it/64X64&text=3'],
['//placehold.it/64X64&text=4'],
['//placehold.it/64X64&text=5']
];
for (var i = 0; i < products.length; i++) {
var image = products[i][0];
imgslider(image, i * 800, i == products.length - 1);
}
};
function imgslider(image, timeout, last) {
window.setTimeout(function() {
document.getElementById('imgslider').innerHTML = "";
var product = document.getElementById('imgslider');
var elem = document.createElement("img");
product.appendChild(elem);
elem.src = image;
if (last) {
setTimeout(startSlide, 800);
}
}, timeout);
}
startSlide()
&#13;
<div id="imgslider"></div>
&#13;
如果要循环,则可以使用setInterval()代替
function startSlide() {
var products = [
['//placehold.it/64X64&text=1'],
['//placehold.it/64X64&text=2'],
['//placehold.it/64X64&text=3'],
['//placehold.it/64X64&text=4'],
['//placehold.it/64X64&text=5']
],
i = 0;
setInterval(function() {
imgslider(products[i][0]);
if (++i >= products.length) {
i = 0
}
}, 800);
};
function imgslider(image) {
document.getElementById('imgslider').innerHTML = "";
var product = document.getElementById('imgslider');
var elem = document.createElement("img");
product.appendChild(elem);
elem.src = image;
}
startSlide()
&#13;
<div id="imgslider"></div>
&#13;
答案 1 :(得分:0)
这是因为window.setTimeout
只调用了一次该函数,因此您应该使用window.setInterval
代替。像这样:
window.setInterval(function () { /* code to update picture... */ }, 3000);
如果它仍然不起作用,您可以检查控制台日志中的错误 IE中的 F12 或Chrome中的 Ctrl + Shift + J 。