javascript - 未捕获的类型错误 : Cannot set property 'src' of undefined

标签 javascript dom

网址:http://www.gws-mbca.org

幻灯片可以在 Firefox 中运行。它曾经在 IE 和 Chrome 中运行。现在我在 IE 和 Chrome 中都收到以下错误:

Uncaught TypeError: Cannot set property 'src' of undefined

该脚本使用 <script type="...> 链接在文档头中。

网页中的代码如下:

<section style="margin: 0 auto; text-align: center;">
  <img src="./rPix/rp1.jpg" id="slide" width="900" height="200" alt="slide show images" />
</section>


<body onload="runShow();">

函数runShow是slideshow.js的一部分 - 代码如下:

/* An automatically rotating slide show using Javascript and the DOM.
   This script cobbled together by Paul D.J. Vandenberg */

var j = 1;
var pix = new Array(11);

for (i = 0; i < pix.length; i++) {
  pix[i] = "rPix/rp"+j+".jpg";
  j++;
}

var index = Math.floor(Math.random() * 11) + 1;
var limit = pix.length - 1;

function runShow() { 
  if (index > limit) {
    index = 0;
  }
  document.slide.src = pix[index];
  setTimeout("runShow()", 10000);
  index++;
}

最佳答案

确保在 id="slide" 元素添加到 DOM 后调用 runShow()

document.slidedocument.getElementById("slide") 的简写。当没有定义具有该 id 的元素时,后者将返回 null

关于javascript - 未捕获的类型错误 : Cannot set property 'src' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16993907/

相关文章:

javascript - 如何将用户提示(输入)存储到数组中并检索它的最大值和最小值?

javascript - Angularjs 中两个按钮的不同验证?

javascript - Polymer 中的数据绑定(bind)

javascript - Linux 服务器 - 路径

jquery - 使用相同的类名获取不同页面上的元素值

javascript - 如何删除 DOM 元素内的所有文本

javascript - React/Redux : Error: Actions must be plain objects. 使用自定义中间件进行异步操作

javascript - 如何访问此 JavaScript 函数中的变量永久链接?

javascript - 选中所有复选框

jquery - 使用 jQuery 进行操作后保持合理的内联 block 元素的合理性