gpt4 book ai didi

javascript - NotFoundError 未找到节点 image_div.parentNode.removeChild(img)

转载 作者:行者123 更新时间:2023-11-28 07:44:43 26 4
gpt4 key购买 nike

我在使removeChild()工作时遇到问题。我收到“NotFoundError:未找到节点 image_div.parentNode.removeChild(img);”错误

这是我的代码:

<div id="imagesframe"> </div>

<script>
images_array = [image1.jpg,image2.jpg,image3.jpg,image4.jpg,image5.jpg];
var image_div = document.getElementById('imagesframe');
for(var i=0 ; i<images_array.length ; i++) {
var img = new Image();
img.src = images_array[i];
img.style.width = '500px';
img.style.height = '500px';
setTimeout(function(){image_div.appendChild(img)},1000);
image_div.parentNode.removeChild(img);
}
</script>

最后一行: image_div.parentNode.removeChild(img);导致了问题。

这可能是什么原因造成的?

最佳答案

将正确的 img 传递给参数函数时,在循环中使用 setTimeout 会使事情变得复杂。另外,您可能省略了数组中图像 URL 周围的引号。

然后是setTimeout,它不会阻止循环的执行,它只是一个计时器,在给定的延迟后启动参数函数。在您的代码中(没有其他错误),一秒钟后所有五个函数调用几乎同时完成,因为循环在微秒内的每一轮上创建一个新的计时器。

这是使用简单外部作用域访问的替代方法。

window.onload = function () {
var imagesArray = ['image1.jpg','image2.jpg','image3.jpg','image4.jpg','image5.jpg'], // URLs of the images
imageDiv = document.getElementById('imagesframe'), // An element wherein to show the images
counter = 0, // Image counter
img; // A temporary image element

// Changes images in an element
function changeImg (first) {
if (!first) { // Check, if there's an image to remove
imageDiv.removeChild(img); // Remove an image
} else { // Reset counter, just in case the slideshow will be reused
counter = 0;
}
// Create a new image and append it to an element
img = new Image();
img.src = imagesArray[counter];
img.style.width = '500px';
img.style.height = '500px';
imageDiv.appendChild(img);
// Show more images or quit
counter += 1;
if (counter < 5) { // Show the next image
setTimeout(changeImg, 1000);
} else { // Remove the last image
setTimeout(function () {imageDiv.removeChild(img)}, 1000);
}
}
changeImg(true); // Show the first image
return;
};

代码被放置在head 并包装在window.onload 中。如果需要,您可以将其包装在 IIFE 中,并将其放置在代码中的原始位置。需要一个包装器来避免声明全局变量。

IIFE = 立即调用函数表达式,它看起来有点像这样:

(function () {/* Code to run here */}());

关于javascript - NotFoundError 未找到节点 image_div.parentNode.removeChild(img),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27571140/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com