我写了一个每3秒更换一次图像的功能。我的问题是,这是一种可以接受的方式来完成这个还是有更好的方法?我之所以这么说是因为这里的一些例子,这样做看起来有点过于复杂。这让我怀疑这些例子中的复杂性是否存在是有原因的,以及我是否遗漏了某些东西。感谢
let timeout= function(){
//encapsulates data
let index=0;
let images=["https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRchcI27Cam2YzkA2vKlTimh6nvER7utm_HyjPu7gjlsljInp9L","https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRchcI27Cam2YzkA2vKlTimh6nvER7utm_HyjPu7gjlsljInp9L","https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcS10D58-5V5cDC8V3vcHC4xKTFqGsnGg4ONyW6Khy-8iWJ9Xzy5xQ"];
$(".gallery").attr("src",images[index]);//sets starting image
return{
run: function(){
!function timeout(){
function changeImg(){
if(index===images.length-1){//resets cycle if needed
index=0;
}
else{
index++
}
$(".gallery").attr("src",images[index]);//changes image
timeout();//repeats
}
setTimeout(changeImg,3000);
}();
}
}
}();
timeout=timeout.run;//redefines timeout as its returned object function run
timeout();//calls timeout
答案 0 :(得分:0)
总是有更好的方式来写一切。 :)
这是我的尝试:
https://jsfiddle.net/f1cgohh3/4/
<html>
<body>
<input type="checkbox" id="grapes" value="grapes" name="fruit" />
<label for="grapes">
<div class="choices">Grapes</div>
</label>
<input type="checkbox" id="Bananas" value="Bananas" name="fruit" />
<label for="Bananas">
<div class="choices">Bananas</div>
</label>
<input type="checkbox" id="Apples" value="Apples" name="fruit" />
<label for="Apples">
<div class="choices">Apples</div>
</label>
<input type="checkbox" id="Strawberries" value="Strawberries" name="fruit" />
<label for="Strawberries">
<div class="choices">Strawberries</div>
</label>
</body>
</html>