2014-12-19 79 views
1

我有問題得到removeChild()的工作。我得到「NotFoundError:未找到節點image_div.parentNode.removeChild(img);」錯誤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); 正在導致此問題。

這可能是什麼原因造成的?

+0

爲什麼你試圖找到從父父的形象呢? 'img.parentNode.removeChild(img)'會更好。雖然,在超時過期之前找不到img。也許你誤解了'setTimeout',它不會延遲其他代碼的執行,它會延遲調用在參數中傳遞的函數。 – Teemu

+0

我什至試過image_div.removeChild(img);但那不行。那麼在這裏有什麼工作?好吧,現在我看到我必須修復setTimeout()函數,現在這更加複雜。看起來我將不得不找出另一個解決方案。 – bioscorpion

+0

請解釋你實際正在做什麼?第二個顯示一個圖像,顯示下一個等等? – Teemu

回答

0

在循環中使用setTimeout會在將正確的img傳遞給參數函數時使事情變得複雜。此外,您可能已經忽略了數組中圖像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 */}()); 
+0

非常感謝你爲這個非常詳細的代碼答案!這不像我原先想象的那麼簡單!遞歸絕對有意義。 – bioscorpion

+0

其實代碼不是遞歸的,它是從外部重新調用的。無論如何,這種類型的實現被廣泛使用超時。你也可以用循環來做到這一點,但這比我的簡單方法更復雜。如果您覺得答案很有用,您可以通過在答案的左上角勾上勾號來接受答案。通過接受答案,其他訪問者可以看到,你的問題得到解決,並且我們都將獲得一些代表 – Teemu

+0

不遞歸?從行 if(counter <5){//顯示下一個圖像 setTimeout(changeImg,1000);它是遞歸的,因爲它是從函數內部調用的。 我想給你投票,但它不會讓我。顯然我需要更多的聲譽才能做到這一點,我認爲這很愚蠢。 – bioscorpion