简体   繁体   English

我如何获得删除按钮以从本地存储中删除单个项目

[英]how can i get get the delete button to remove a single item from local storage

When I add a new item to the list it creates a delete button for that specific item. 当我向列表中添加新项目时,它将为该特定项目创建一个删除按钮。 I would like to know how I can get the delete button to remove that item from the list without deleting all the other items and also removing it from local storage. 我想知道如何获取删除按钮以从列表中删除该项目,而不删除所有其他项目,也将其从本地存储中删除。 I have tried before to get it to work but no luck. 我曾经尝试过使其工作,但没有运气。

<div class = 'wrapper'>
    <h2>Tapas Order</h2    
    <p></p>
    <ul class="plates">
        <li>Loading Tapas...</li>
    </ul>   
    <ul>
        <form class='add-items'>
            <input type='text' name='item' placeholder='Item Name' required>
            <input type='submit' value='+ Add Item'> 
        </form>
    </ul>
</div>

<script>
    const addItems = document.querySelector('.add-items');
    const itemsList = document.querySelector('.plates');
    const items = JSON.parse(localStorage.getItem('items')) || [];

    function addItem (e){
        e.preventDefault();
        const text = this.querySelector('[name=item]').value;
        const item = {
            text,
            done: false
        };
        items.push(item);
        populateList(items, itemsList);
        localStorage.setItem('items', JSON.stringify(items));
        this.reset();
    }

    function populateList(plates = [], platesList){
        platesList.innerHTML = plates.map((plate, i) => {
            return`
            <li>
                <input type='checkbox' data-index=${i} id='item${i}' ${plate.done ? 'checked' : ''}/>
                <label for='item${i}'>${plate.text} </label>
                <button id='delete'>delete</delete>
            </li>  
            `;
        }).join('');
    }

    function toggleDone(e){
        if(!e.target.matches('input')) return; 
        const el = e.target;  
        const index = el.dataset.index;
        items[index].done = !items[index].done;
        localStorage.setItem('items', JSON.stringify(items));
        populateList(items, itemsList);
    }

    addItems.addEventListener('submit', addItem);
    itemsList.addEventListener('click', toggleDone);
    populateList(items, itemsList);

</script>

Just modified your code slightly :) 刚刚稍微修改了代码:)

add this onclick to your button creation: 将此onclick添加到您的按钮创建中:

<button id='delete' onclick="javascript:deleteItem(this,${i})">delete</delete>

and add this function to your script: 并将此功能添加到脚本中:

function deleteItem(item,index){
    //Azurethi was here!
    items.splice(index, 1);
    localStorage.setItem('items', JSON.stringify(items));
    item.parentNode.remove();
    populateList(items, itemsList);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM