// create array populate with 4 list items
let arr = ['apples', 'pears', 'blackberries', 'blueberries'];
// create a function
const populateList = array => {
// create a for loop to run through list items
for (let i = 0; i < array.length; i++) {
// for each list item, create a list item element
let listItem = document.createElement('li');
// populate list item with array item in iteration
listItem.innerHTML = array[i];
// create span element
// let spanElement = document.createElement('span');
// append list item element with span item containing unicode: \u00D7
listItem.innerHTML += "<span class='close'>\u00D7</span>";
// append unordered list with list item as child element
document.getElementById('itemList').appendChild(listItem);
}
return console.log(document.getElementById('itemList').innerText);
}
function updateList () {
let selectedItem = [document.getElementById('input').value];
if (selectedItem == "") {
alert(`Please, insert an item!`);
} else {
arr.push(document.getElementById('input').value);
document.getElementById('input').value = "";
return populateList(selectedItem);
}
}
populateList(arr);
document.querySelectorAll('.close').forEach(item => {
item.addEventListener('click', deleteFunction => {
for (i=0;i<arr.length;i++)
console.log(spanElements[i].parentNode.innerText.slice(0, -1));
// Problems here: my click event triggers all list items to
// repopulate. How can I isolate a click press event so when
// I click on HTML I can retrieve a single value and remove
// that matching item from my array and repopulate the HTML
// list without the value removed?
})
})
1条答案
按热度按时间vtwuwzda1#
您需要将
id
添加到span
元素,以便从事件参数中获取对单击的element
的引用。在单击事件后,您需要从数组中删除条目,清除div容器,然后调用populate list沿着addEventListerner
,因为旧的侦听器将被删除。第一个