我在论坛中搜索了为什么在调用 getElementById
时我的 img 为 null
,并且我已将脚本移至 img 下方,但我仍然得到图像为 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
。
我希望能帮助您理解它为何为空。谢谢。
最佳答案
您要删除具有该 ID 的图像,然后下次您的代码通过时,它就找不到具有该 ID 的任何图像。
您需要在要替换旧图像的新图像上设置该 ID。
像这样
// An image element for loading our next image
var ourImage = new Image();
ourImage.id='irimg';
关于JavaScript 无法读取 null 的属性 'parentElement',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40379180/