1

我有这个函数试图改变 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>

是什么赋予了?

4

2 回答 2

0

Javascript 在解析后立即执行。

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

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

于 2013-01-18T19:05:58.953 回答
-1

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

所以尝试这样的事情。

<html>
   <head>
   <script>
      function F () { /*reach element*/ }
   </script>
</head>
<body>
   //The element
</body>
<script>
   F ();
</script>
</html>
于 2013-01-18T19:08:15.763 回答