2017-08-11 58 views
0

我該如何刪除數組的當前實例,而不是數組的所有實例?如何刪除數組的當前實例,而不是數組的所有實例?

var persons = []; 

showAllButton.onclick = function() { 

    while (showList.firstChild)showList.removeChild(showList.firstChild); 

創建新的節點實例。

for (var l in persons) { 
    var listNode = document.createElement("LI"); 
    var btn = document.createElement("BUTTON"); 
    btn.innerHTML = "Remove"; 
    showList.appendChild(listNode); 
    showList.appendChild(btn); 

正確顯示推送的實例。

listNode.innerHTML = 
    '<p><b>Full Name:</b> ' + persons[l].firstName +' ' + persons[l].lastName + '</p>' + 
    '<p><b>Phone:</b> ' + persons[l].phone + '</p>' + 
    '<p><b>Address:</b> ' + persons[l].address + '</p>' 
    } 

嘗試了以下功能的一些變化,但只是清空陣列,或者至少不會返回修正陣列。

btn.onclick = function() { 
     var index = Array.indexOf(persons[l]); 
     persons.splice(index, 1);    
     return persons; 
    } 



    if (showAllButton.value=="Show Contacts") { 
     showAllButton.value = "Hide Contacts"; 
     showList.style.display = "block"; 
    } 


    else if (showAllButton.value = "Hide Contacts") { 
     showAllButton.value = "Show Contacts"; 
     showList.style.display = "none"; 
    }  

}

+2

看看*閉合內循環* –

+0

'Array.indexOf(persons [l]);'?這應該做什麼? –

+1

'else if(showAllButton.value =「Hide Contacts」)'不會將值與字符串文字進行比較,而是分配值。 –

回答

1

可能綁定L,在標l刪除元素,然後重繪DOM莫名其妙:

btn.onclick = function(l) { //take over the bound l 
    persons.splice(l, 1);    
    //some kind of redraw 
    showAllButton.click(); 
}.bind(null,l);//bind l 
0

像這樣的東西應該按預期工作(對不起,盲目的編碼,現在沒有時間測試)

var persons = []; 
function removePerson(index) { 
    persons.splice(index, 1); 
    renderList(); 
} 

function clearList() { 
    while (showList.firstChild) { 
     showList.removeChild(showList.firstChild); 
    } 
} 

function renderItem(person, index) { 
    var item = showList.appendChild(document.createElement("LI")); 

    var label = item.appendChild(document.createElement("SPAN")); 
    label.innerHTML = persons[i]; 

    var btn = item.appendChild(document.createElement("BUTTON")); 
    btn.innerHRML = "Remove"; 
    btn.onclick = removePerson.bind(null, index); 
} 

function renderList() { 
    clearList(); 
    persons.forEach(renderItem); 
} 

沒有一種最佳實踐,但似乎工作。

0

最後工作代碼,謝謝!

showAllButton.onclick = function() { 

while (showList.firstChild)showList.removeChild(showList.firstChild); 

for (var l in persons) { 
var list = showList.appendChild(document.createElement("LI")); 
list.innerHTML = 
'<p><b>Full Name:</b> ' + persons[l].firstName +' ' + persons[l].lastName + '</p>' + 
'<p><b>Phone:</b> ' + persons[l].phone + '</p>' + 
'<p><b>Address:</b> ' + persons[l].address + '</p>'; 

var btn = showList.appendChild(document.createElement("BUTTON")); 
btn.innerHTML = "Remove"; 
btn.onclick = function(l) { 
    persons.splice(l, 1); 
    showAllButton.click(); 

}.bind(null,l); 

} 
相關問題