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

时间:2018-06-24 21:38:19

标签: javascript html local-storage

当我向列表中添加新项目时,它将为该特定项目创建一个删除按钮。我想知道如何获取删除按钮以从列表中删除该项目,而不删除所有其他项目,也将其从本地存储中删除。我曾经尝试过使其正常工作,但是没有运气。

<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>

1 个答案:

答案 0 :(得分:0)

只需稍微修改您的代码即可:)

将此onclick添加到您的按钮创建中:

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

并将此函数添加到脚本中:

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