我已經搜索論壇,爲什麼我的img是null
,當調用getElementById
時,我已將腳本移動到img下面,但是我仍然收到圖像是null
。Javascript無法讀取屬性'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
。
我很感謝幫助理解爲什麼它爲空。謝謝。
使用丁目的調試模式(F12),在該行'oldImage.parentElement.insertBefore(ourImage,oldImage)斷點;',移動光標在'oldImage'之上,看看顯示的是什麼(tooltip-style pop)。 – FDavidov
可能是在頁面完全加載之前腳本正在運行,這意味着該圖層尚未渲染。通常情況下,如果你有一個訪問DOM元素的腳本,你需要確保它們在你嘗試訪問它們之前先被加載到DOM中。在頁面加載完成後運行腳本,而不是立即運行 – Jayce444
同意@ Jayce444作爲可能的來源。行使我的建議可能會給你一些提示。 – FDavidov