2011-02-24 38 views
1

父母被這一個掙扎,我有以下DOM結構:卸下兩個孩子及其使用Javascript

<ol id="add_images"> 
    <li> 
     <input type="file" /><input type="button" name="removeButton" /> 
    </li> 

    <li> 
     <input type="file" /><input type="button" name="removeButton" /> 
    </li> 

    <li> 
     <input type="file" /><input type="button" name="removeButton" /> 
    </li>  

基本上我試圖消除所有的孩子和家長包含(李標籤)點擊刪除按鈕。

我嘗試過每種方式的parentNode和removeChild組合。通過下面的JavaScript,我只能找到孩子,而不是父母。

function addFile(addFileButton) { 
    var form = document.getElementById('add_images'); 
    var li = form.appendChild(document.createElement("li")); 

    //add additional input fields should the user want to upload additional images.  
    var f = li.appendChild(document.createElement("input")); 
    f.className="input"; 
    f.type="file"; 
    f.name="files[]"; 

    //add a remove field button should the user change their mind 
    var rb = li.appendChild(document.createElement("input")); 
    rb.type="button"; 
    rb.value="Remove File"; 
    rb.onclick = function() {//This is where the problem is 
     li.removeChild(this.parentNode); 
     li.removeChild(this); 
    } 
} 

我相信它的東西很簡單。謝謝你的幫助。

回答

2

由於您要刪除<li>,因此您需要從其父節點ol中執行此操作。

li.parentNode.removeChild(this.parentNode); 

您也可以使用form變量已經是對ol參考。

form.removeChild(this.parentNode); 

或:

form.removeChild(li); 

或者你可以以避免創造一個封閉做到這一切不變量。

this.parentNode.parentNode.removeChild(this.parentNode); 
+0

哇。非常簡單地感謝您的幫助 – 2011-02-24 02:44:48

+0

@Gerry Bunker:不客氣。 – user113716 2011-02-24 02:45:20

+0

hrmm,從來沒有想過這樣。我從最不共同的角度看它。即;從刪除按鈕開始,按照dom的方式工作。我會記住下次。 – 2011-02-24 02:58:07

相關問題