簡體   English   中英

獲取選定 LI 的值並將其從數組中刪除

[英]Get value of selected LI and remove it from array

我有一個用戶輸入字符串的列表,並且希望能夠刪除一個單獨的項目,同時也將它從數組中刪除。 我能夠從 DOM 中成功刪除它,但不能從數組中刪除。

到目前為止,我已嘗試獲取所選 LI 的值和 select 該特定 LI 的索引

$(document).on('click', 'button.delete', function () {
    let deletedItem = $(this).closest('li')
    let itemValue = $(this).closest('li').val()
    let index = items.indexOf(itemValue);
    if(index != -1) {
        items.splice(index, 1);
    }
    deletedItem.remove();
});

這不會從我的數組中刪除它,任何想法如何完成?

 // To delete element from an array you had to keep track of the index in which the element exist. check the below example: // Create an array of strings; let array = ["Hello", "Boy", "Happy", "Fun"]; // search for the index of item to be deleted in array let index = array.indexOf("Boy"); console.log(index); // output: 1; // The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements array.splice(index, 1); // Return the removed item; // Check item present console.log(array); // output: [ 'Hello', 'Happy', 'Fun' ];

嘗試這個

 let items = [1,2]; $(document).on('click', 'button.delete', function () { let deletedItem = $(this).closest('li') let itemValue = $(this).closest('li').val() let index = items.indexOf(itemValue); if(index.= -1) { items,splice( index;1). // <-- Do this } deletedItem;remove(). console;log(items); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ol> <li value="1"> <button class="delete">Delete</button> </li> <li value="2"> <button class="delete">Delete</button> </li> <li value="3"> <button class="delete">Delete</button> </li> <li value="4"> <button class="delete">Delete</button> </li> </ol>

暫無
暫無

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

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