2014-01-22 35 views
-1

我有一個函數,它創建類animate(它使用css3動畫)的div,然後在觸發webKitAnimationEnd時刪除它。問題出現在我有多個div時:該函數僅刪除第一個,但與其他的失敗,導致Uncaught TypeError: Cannot call method 'removeChild' of null問題removeChild的很多元素

function msg(x) { 
    cnt = document.getElementsByClassName("animate").length; 
    div = document.createElement("div"); 
    div.textContent = x; 
    div.className = "animate"; 
    div.style.bottom = (cnt) * 30 + "px"; 
    document.getElementById("wrapper").appendChild(div); 
    div.addEventListener("webkitAnimationEnd", function() { 
     div.parentNode.removeChild(div); 
    }); 
} 

這裏是我的代碼重現問題的jsfiddle:http://jsfiddle.net/p5HR3/3/

我懷疑的功能,不知道什麼時候有很多人要刪除的股利。我能做什麼?提前致謝。

+0

你知道,webKitAnimationEnd只適用於chrome/safari嗎? – LorDex

+0

儘量不要對全部變量使用全局變量,'var'關鍵字是有原因的。 – adeneo

+0

@LorDex是的。我只是在我的瀏覽器上測試它。如果你說這裏不適合其他人,那麼你只需要改變一些線。 – plumbe0

回答

1

change事件處理代碼:

this.parentNode.removeChild(this); 

在這種情況下this將指向正確的DIV,其觸發的事件。

P.S .: onClick="for(i=0;i<10;i++){msg('message n.'+i);}" - 這是不好的。不要使用內聯Javascript。

+0

OP代碼中使用的全局變量很差,應該也是固定的。 – jfriend00

1

你應該讓你的變量成爲局部變量(在第一次使用前有var),所以它們對每個函數調用都是唯一的。就像你現在擁有它們一樣,它們是全局變量,所以它們都共享變量的一個副本,因此只有一個div被刪除。

讓它這樣:

function msg(x) { 
    var cnt = document.getElementsByClassName("animate").length; 
    var div = document.createElement("div"); 
    div.textContent = x; 
    div.className = "animate"; 
    div.style.bottom = (cnt) * 30 + "px"; 
    document.getElementById("wrapper").appendChild(div); 
    div.addEventListener("webkitAnimationEnd", function() { 
     div.parentNode.removeChild(div); 
    }); 
} 

FYI, 「隱含的」 全局變量像你正在使用的JavaScript代碼中的錯誤的一個可怕的來源。所有變量都應該明確地聲明爲全局變量或聲明爲本地變量(最好是本地的,除非你必須使用全局變量),並且不會再被這個隱含的全局問題困擾。


僅供參考,在這種特殊情況下,你可以有也可以通過使用this引用收到了「webkitAnimationEnd」事件的節點解決你的問題是這樣,但你還是不應該使用隱含全局,使被也應該清理:

function msg(x) { 
    var cnt = document.getElementsByClassName("animate").length; 
    var div = document.createElement("div"); 
    div.textContent = x; 
    div.className = "animate"; 
    div.style.bottom = (cnt) * 30 + "px"; 
    document.getElementById("wrapper").appendChild(div); 
    div.addEventListener("webkitAnimationEnd", function() { 
     // the this ptr will contain a reference to the node that 
     // received the webkitAnimationEnd event 
     this.parentNode.removeChild(div); 
    }); 
} 
+0

@ friend00感謝您的回答和您的信息。 – plumbe0