2014-02-13 136 views
-5

我在使用此代码时遇到了一些麻烦,我在网上进行了测试,但似乎无法正常工作。这是我所有的编码:
为什么这个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 = ["","","","","",""] 

而且我知道在链接数组未填写,但我已准备好链接。他们只是图片,所以你可以填写任何你想要的网址,如果你正在测试它。

有人可以说我在做这个代码错了吗?

+6

JavaScript中没有'wait'功能。 –

+1

'changeimage'永远不会被执行。 – deceze

回答

4
  1. 根据你运行它,document.getElementById("image1")可能会返回一个元素或null。如果返回null,当您尝试访问src属性并中止时,该脚本将会出错。
  2. 你永远不会打电话changeimage函数
  3. 在JavaScript中没有wait函数,你似乎没有定义一个函数。
  4. return img,让你退出的第一次你周围的环
  5. go如果你想要一个新的URL分配给img,那么你也只是指定的URL变量的函数。 img将是一个包含字符串的变量。它不会引用src属性。

如果你想这样做,你需要彻底改变你的方法。

// 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); 
-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(函数(){警报( “你好”)},3000);

+0

setTimeout而不是setInterval – R3tep