2016-11-02 43 views
1

我已經搜索論壇,爲什麼我的img是null,當調用getElementById時,我已將腳本移動到img下面,但是我仍然收到圖像是nullJavascript無法讀取屬性'parentElement'null

這裏是我的代碼:

<!DOCTYPE html> 
<html> 
<head> 
</head> 
<body> 
<img id="irimg" src="ir.bmp" alt="Video Stream" style="width:640px;height:480px;"> 
<script type="text/javascript"> 
function loadNextImage() { 
    // An image element for loading our next image 
    var ourImage = new Image(); 

    // Setup the event handlers before setting the source 
    ourImage.onload = function() { 
     // Request the next frame 
     requestAnimationFrame(loadNextImage); 

     // Swap out the image element on the page with the new one 
     var oldImage = document.getElementById('irimg'); 
     oldImage.parentElement.insertBefore(ourImage, oldImage); 
     oldImage.parentElement.removeChild(oldImage); 
    }; 

    ourImage.onerror = function(){ 
     // Something went wrong with this frame. Skip it and move on. 
     requestAnimationFrame(loadNextImage); 
    } 

    // Finally load the image 
    ourImage.src = "ir.bmp?" + new Date().getTime(); 
}; 

requestAnimationFrame(loadNextImage); 
</script> 
</body> 
</html> 

的錯誤是發生在這裏:

var oldImage = document.getElementById('irimg'); 
oldImage.parentElement.insertBefore(ourImage, oldImage); 

Chrome所給出的誤差爲Uncaught TypeError: Cannot read Property 'parentElement' of null

我很感謝幫助理解爲什麼它爲空。謝謝。

+0

使用丁目的調試模式(F12),在該行'oldImage.parentElement.insertBefore(ourImage,oldImage)斷點;',移動光標在'oldImage'之上,看看顯示的是什麼(tooltip-style pop)。 – FDavidov

+0

可能是在頁面完全加載之前腳本正在運行,這意味着該圖層尚未渲染。通常情況下,如果你有一個訪問DOM元素的腳本,你需要確保它們在你嘗試訪問它們之前先被加載到DOM中。在頁面加載完成後運行腳本,而不是立即運行 – Jayce444

+0

同意@ Jayce444作爲可能的來源。行使我的建議可能會給你一些提示。 – FDavidov

回答

2

您正在使用該ID刪除圖像,然後下次您的代碼通過它時,無法找到具有該ID的任何圖像。

您需要在新圖片上設置您要替換舊圖片的ID。

像這樣

// An image element for loading our next image 
var ourImage = new Image(); 
ourImage.id='irimg'; 

見:https://jsfiddle.net/9Lp1724v/

+0

謝謝你這個工作。我可以在5分鐘內接受。 – PhilBot