为什么这个JavaScript不起作用?

时间:2014-02-13 17:23:26

标签: javascript

我在使用这段代码时遇到了一些问题,我在网上测试了它,但似乎没有用。这就是我的全部编码:

我的HTML:

<img src="kruisje.jpg" id="image1">

脚本应该是幻灯片,但不是:

var img = document.getElementById("image1").src;
        function changeimage(){
            wait(10)
            for(var i = 0; i < images.length; i++){
                return img
            }   
        }   
        var images = ["","","","","",""]

我知道数组中的链接没有填写,但我已准备好了链接。它们只是图片,因此您可以在测试时填写所需的任何网址。

有人能说我在这段代码上做错了吗?

2 个答案:

答案 0 :(得分:4)

  1. 根据 运行时,document.getElementById("image1")可能会返回元素或null。如果它返回null,则当您尝试访问src属性并中止时,脚本将会出错。
  2. 您永远不会调用changeimage函数
  3. JavaScript中没有wait函数,您似乎没有定义一个函数。
  4. return img,所以你第一次绕过循环就退出了这个功能
  5. 如果您想为img分配一个新网址,那么您只需将该网址指定给该变量即可。 img将是一个包含字符串的变量。它不会引用src属性。
  6. 如果你想这样做,你需要彻底改变你的方法。

    // Get a reference to the element (make sure you run this *after* the image has been added to the DOM)
    var img = document.getElementById("image1");
    
    // Track where you are in the array
    var imagesIndex = 0;
    var images = ["","","","","",""]
    
    function changeImage(){
        // Assign the new URL to the src property of the image
        img.src = images[imagesIndex];
        // Increment the index here
        imageIndex++;
        // Check if it has gone off the end and reset it if it has
        if (imageIndex >= images.length) {
            imageIndex = 0;
        }
    }
    
    // Call the function on your time period
    setInterval(changeImage, 10000);
    

答案 1 :(得分:-2)

var img = document.getElementById("image1").src;
        function changeimage(){
            wait(10) // ERROR FUNCTION
            setTimeout(function(){alert("Hello")},3000);
            for(var i = 0; i < images.length; i++){
                return img
            }   
        }   
        var images = ["","","","","",""]

你需要使用setTimeout(function(){alert(“Hello”)},3000);

相关问题