get "Cannot set property 'src'null"但是这个元素是

Getting "Cannot set property 'src' of null" but the element exists

本文关键字:quot 元素 null set property get src Cannot      更新时间:2023-09-26

我有这个函数,它试图改变一个img的src属性。下面是Javascript:

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

我的谷歌chrome控制台说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>

给了什么?

Javascript在被解析后立即执行。

如果你的JS包含在你的网页的<head>中,它将在文档主体被解析和DOM被构建之前执行。

因此,您需要设计您的代码,以便在加载DOM之前不会执行它。你可能需要查看DomContentLoaded事件的MDN文档。或者,您可以使用许多JavaScript库之一,它们为您打包了这些。

如果chrome显示该元素为空,它就是空的。也许您在DOM中加载元素之前调用函数。就像在元素标签之前调用head标签中的函数。

所以试试这样做。

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