2013-01-18 62 views
1

我有這個函數試圖改變img的src屬性。下面是使用Javascript:獲取「無法設置null的屬性'src'」,但元素存在

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> 

什麼給?

+3

你什麼時候調用函數? – SLaks

+3

'setTimeout()'調用需要'setTimeout(transition,1000);' – Pointy

+2

@SLaks我認爲很清楚它在元素在頁面之前被調用,否則遞歸會被炸燬。 – Pointy

回答

0

JavaScript在解析後立即執行。

如果您的JS包含在您的網頁的<head>中,它將在文檔正文解析並且DOM已經構建之前執行。

因此,您需要設計您的代碼,以便在DOM加載之前不會執行代碼。您可能想查看DomContentLoaded事件上的MDN docs。或者,您可以使用其中的一個JavaScript庫,它可以爲您提供這些庫。

+0

謝謝。我通過改變setTimeout(transition()...到setTimeout(transition)來修復它,正如Pointy所建議的那樣。 –

-1

如果chrome表示元素爲null,則爲null。也許你在元素加載到DOM之前調用函數。比如在元素標籤之前調用head標籤中的函數。

所以嘗試這樣的事情。

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