首页 > 解决方案 > Splice() 方法删除不在索引处的数组末尾

问题描述

我的功能removeItems()是从 li 元素中的列表项中删除项目。目前我可以从视图中删除该项目,但数组拼接方法会从数组末尾而不是索引处删除元素。

我的代码是:

var data = [
    "Tuesday ",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday", 
    "Sunday"
];

function itemArray(ele) {
    let items = ''; 
    for (let i = 0; i < ele.length; i++) {
        items += `<li>${ele[i]} <button type='button' class='removeItem'>Remove Item</button> </li>`;
    }
    return items;
}

function addItemFunction () {
    const addButton = document.getElementById('addButton');
    const input = document.getElementById('input').value;
    data.push(input);    
    htmlInside(data);  
}

function removeItemFunction() {
    data.pop(data);    
    htmlInside(data);
}

function removeItems() {
    const listUl = main.querySelector('ul');
    listUl.addEventListener('click', (event) => {
        if (event.target.tagName == 'BUTTON') {
          let li = event.target.parentNode;
          let ul = li.parentNode;
          ul.removeChild(li);
          var index = data.indexOf(data);
          data.splice(index, 1);
          console.log(data);
        }
      });
}

function htmlInside(data) {
        let getHtml = `
    <ul class="listItems">
        ${itemArray(data)}
        
    </ul>
    <input type='input' id='input' required></input><button type='button' id='addButton'>Add item</button><button id='removeButton'>Remove item</button>
    
    `
    document.querySelector('.hero').innerHTML = getHtml;

    addButton.addEventListener('click', function () {
        addItemFunction();
    });

    removeButton.addEventListener('click', function () {
        removeItemFunction();
    });

    removeItems();

 }  

我认为我没有正确找到数据的索引。可能是一个问题var index = data.indexOf(this); data.splice(index, 1);

当我console.log(index)记录-1。

标签: javascriptarraysindexofarray-splice

解决方案


问题是在这一行中var index = data.indexOf(data),您正在检查数据的索引,您应该检查数据数组中元素的索引,因此您应该首先从列表中获取该元素 ele=li.textContent,然后将其传递给data.indexOf(ele)


推荐阅读