【问题标题】:Getting "Cannot set property 'src' of null" but the element exists获取“无法设置属性'src' of null”但元素存在
【发布时间】:2013-01-02 13:38:06
【问题描述】:

我有这个函数试图改变 img 的 src 属性。这是Javascript:

function transition(){
    document.getElementById("firstfirst").src = marray[currArrayValue];
    currArrayValue++;
    if(currArrayValue == array.length-1){
        currArrayValue = 0;
    }
    setTimeout(transition(), 1000);
}

我的谷歌浏览器控制台说 document.getElementById("firstfirst") 不存在,但它确实存在。这是 HTML:

<div id="banners-container">
    <div id="banners">
        <img src="images/banners/top-banner-one.png" id="firstfirst" alt="Subscribe now to get access to thousands of vintage movies!" border="0">
    </div>
</div>

什么给了?

【问题讨论】:

  • 你什么时候调用这个函数?
  • setTimeout() 调用必须是 setTimeout(transition, 1000);
  • @SLaks 我认为很明显它是在元素出现在页面上之前被调用的,否则递归就会被破坏。
  • 你能在 JsFiddle 中重现这个吗?
  • 图片显示后是否调用该函数?还是在正文完全加载之前进行了 javascript 调用?

标签: javascript null document getelementbyid


【解决方案1】:

Javascript 在解析后立即执行。

如果你的JS包含在你网页的&lt;head&gt;中,它会在文档正文被解析和DOM构建完成之前执行。

因此,您需要对代码进行设计,使其在加载 DOM 之前不会执行。您可能想查看 DomContentLoaded 事件中的 MDN docs。或者,您可以使用众多 JavaScript 库之一,这些库为您完成了这一点。

【讨论】:

  • 谢谢。我通过将 setTimeout(transition()... 更改为 setTimeout(transition,正如 Pointy 建议的那样修复它。
【解决方案2】:

如果 chrome 表示该元素为 null,则它为 null。也许您在元素加载到 DOM 之前调用函数。就像在元素标签之前调用头部标签中的函数一样。

所以试试这样的。

<html>
   <head>
   <script>
      function F () { /*reach element*/ }
   </script>
</head>
<body>
   //The element
</body>
<script>
   F ();
</script>
</html>

【讨论】:

    猜你喜欢
    • 2017-03-12
    • 2016-11-01
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多