[英]How can I reuse a function properly?
我嘗試制作3個基本幻燈片。
我為第一個編寫了此代碼,並希望通過New slideS()方法和一些參數更改在其他兩個代碼上使用它。但是它不起作用,即使我將參數放入第一個函數也不起作用。它。
有人可以向我解釋為什么這不起作用以及如何解決它嗎?謝謝!
var img = document.getElementById("asd");
var imgArr = ["1.jpg", "3.png", "3.png"];
var i = 0;
function slideS(a) {
a.src = imgArr[i];
if (i < imgArr.length - 1) {
i++;
} else {
i = 0;
}
setTimeout("slideS()", 1500);
}
slideS(img)
您可以使用面向對象的方法執行以下操作:
function SlideShow(el, imagesArray, msDelay) {
this.el = el;
this.images = imagesArray;
this.delay = (msDelay) ? msDelay : 1000;
this.timer = null;
this.Run = function () {
var self = this;
var index = 0;
this.timer = setInterval(function(){
self.el.src = self.images[index++ % self.images.length];
}, this.delay);
}
this.Stop = function() {
this.timer = null;
}
}
var img = document.getElementById("asd");
var imgArr = ["1.jpg", "3.png", "3.png"];
var delay = 1500;
var ss = new SlideShow(img, imgArr, delay);
ss.Run();
...
ss.Stop();
那對你有用嗎? 然后,您將使用純函數和可用於開始,停止和管理任何幻燈片放映的對象。
您可以對元素和數組使用閉包,並使用setInterval
代替setTimeout
。
function slide(id, array) { function swap() { image.src = array[i]; i++; i %= array.length; } var image = document.getElementById(id), i = 0; setInterval(swap, 1500); } slide('image1', ['http://lorempixel.com/400/200/', 'http://lorempixel.com/400/200/', 'http://lorempixel.com/400/200/']);
<image id="image1"></image>
我想你想像:
刪除setTimeout。 並使用setInterval:
setInterval(function(){
slideS(img)
},1500)
試試這個...你在某些地方犯了錯誤
var img = document.getElementById("asd");
var imgArr = ["1.jpg", "3.png", "3.png"];
var i = 0;
function slideS(a) {
a.src = imgArr[i];
if (i < imgArr.length - 1) {
i++;
} else {
i = 0;
}
setTimeout(() => slideS(a), 1500);
/* you need to pass function to setTimeout and pass refrence of image that's 'a' */
// or use function instead of arrow function
setTimeout(function() { slides(a) }, 1500);
}
slideS(img)
希望這可以幫助..
我假設函數不帶參數時可以使用嗎?
然后,它不使用任何參數但停止使用參數的原因是setTimeout嘗試遞歸調用該函數但不傳遞參數。 所以你將其更改為
setTimeout(() => {slideS(a);}, 1500);
但是,當您嘗試同時運行多個實例時,就會遇到麻煩,因為您正在使用全局變量。 例如,您需要為LCV使用更本地的內容(可能是閉包?)。
您必須使用setInterval而不是setTimeout
var img = document.getElementById("asd"); var imgArr = ["https://i.stack.imgur.com/lgt0W.png", "https://i.stack.imgur.com/X0fKm.png", "https://i.stack.imgur.com/YfPSD.png"]; var i = 0; function slideS(a) { a.src = imgArr[i]; if (i < imgArr.length - 1) { i++; } else { i = 0; } } slideS(img); //initial call to start it without having to wait for 1500 ms to pass setInterval(function() { slideS(img); }, 1500);
<img id="asd">
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.