簡體   English   中英

Splice() 方法刪除不在索引處的數組末尾

[英]Splice() method removes end of array not at index

我的 function 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);的問題var index = data.indexOf(this); data.splice(index, 1);

當我console.log(index)它的日志-1。

問題在於這一行var index = data.indexOf(data)您正在檢查數據的索引,您應該檢查數據數組中元素的索引,因此您應該首先從列表中獲取該元素,例如ele=li.textContent然后將其傳遞給data.indexOf(ele)

在點擊事件監聽器中, console.log返回data.splice(index, 1)的值。 你應該看到的是-1。 現在,如果您將 -1 放入拼接中,它將從末端向后開始,在這種情況下是最后一個元素並刪除它。

這是因為.indexOf方法在沒有找到任何東西時返回 -1,這里就是這種情況。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM