如何只删除数组的当前实例,而不是删除数组的所有实例?
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";
}
}
答案 0 :(得分: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