创建一个删除函数来从HTML列表和填充列表项的数组中删除项?

jei2mxaa  于 2022-12-09  发布在  其他
关注(0)|答案(1)|浏览(110)
// 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?

    })
  })
vtwuwzda

vtwuwzda1#

您需要将id添加到span元素,以便从事件参数中获取对单击的element的引用。在单击事件后,您需要从数组中删除条目,清除div容器,然后调用populate list沿着addEventListerner,因为旧的侦听器将被删除。

  • 注意-理想的方法是直接删除元素,而不是一次又一次地重新呈现元素。这样,您就不会重画和重新初始化事件侦听器。*

第一个

相关问题