尝试从列表JavaScript

时间:2017-03-19 17:25:44

标签: javascript

我有一个清单:

var images = ["image1.png", "image2.png", "image3.png", "image4.png"];

我制作了一个代码,当页面加载时会尝试显示image1,但是在3秒内,图像会变为列表中的下一个图像。但是当代码运行时,它被卡在image1上并且在接下来的3秒内没有改变。

到目前为止,这是我的JavaScript代码:

<html>
<body>
<body onload = "myFunction()">
<img src ="image1.png" id = "target" >
<script language="javascript">
    var counter = 0;
    var images = ["image1.png", "image2.png", "image3.png", "image4.png"];

function myFunction() {
   counter++;
   if (counter > 4) {
       counter = 0
   }
   target = document.getElementById ("target").src = images[counter];
   setTimeout("myFunction", 3000) 

   }
window.onLoad = function(){
myFunction(); 
}
</script>
</body>
</html>

我见过类似的代码但回答的答案不符合我的规范。

5 个答案:

答案 0 :(得分:2)

您可以使用setInterval(传递函数而不是字符串)而不是递归调用setTimeout。另请注意,使用模(counter)运算符可以大大简化%逻辑:

<html>

<body>
  <img src="image1.png" alt="image1.png" id="target">
  <script language="javascript">
    var counter = 0;
    var images = ["image1.png", "image2.png", "image3.png", "image4.png"];
    var target = document.getElementById("target")

    setInterval(function myFunction() {
      counter = (counter + 1) % images.length
      target.src = target.alt = images[counter]
    }, 3000)
  </script>
</body>

</html>

答案 1 :(得分:1)

setInterval中,您需要将函数myFunction作为参数传递,不是函数名称"myFunction"

将其更改为:

 setTimeout(myFunction, 3000);

答案 2 :(得分:1)

setTimeout - 只能工作一次 setInterval - 将一直持续

<html>
<body>
<img src ="logo.png" id = "target" >


<script language="javascript">
var counter = 0;
var images = ["logo.png", "222.jpg"];

function myFunction() {
  counter++;

  if (counter > 1) {
       counter = 0
  }
  target = document.getElementById("target").src = images[counter];
}

function my2(){
  setInterval("myFunction()", 1000);
}

window.onload = function(){
my2();
}
</script>

</body>
</html>

答案 3 :(得分:0)

扩展其他人已提及的内容。

  1. 它的窗口。 onload - 不是窗口。 onLoad - 套管很重要
  2. 更新到

    setTimeout(myFunction, 3000);  
    
  3. 将其放在您的window.onload

  4. JS:

    var counter = 0;
    var images = ["image1.png", "image2.png", "image3.png", "image4.png"];
    
    function myFunction() {
       counter++;
       if (counter > 4) {
           counter = 0
       }
       target = document.getElementById ("target").src = images[counter];
    }
    
    window.onload = function(){
        setTimeout(myFunction, 3000) 
    }
    

答案 4 :(得分:0)

您可以使用setInterval代替setTimeout

var counter = 0;
var images = ["image1.png", "image2.png", "image3.png", "image4.png"];
function myFunction() {
   counter++;
   if (counter > 3) {
       counter = 0
   }
   target = document.getElementById("target").src = images[counter];
}

setInterval(myFunction, 3000);

JSFiddle