简体   繁体   English

如何从 localstorage onclick 的数组中删除项目

[英]How to delete an item from an array from localstorage onclick

I have the following code.我有以下代码。 It stores the info on localstorage each time the user clicks on an "add to cart" button:每次用户单击“添加到购物车”按钮时,它都会将信息存储在本地存储中:

let addCartItemButtons = document.getElementsByClassName('product-description-add')
for (let i = 0; i < addCartItemButtons.length; i++){
    let button = addCartItemButtons[i]
    button.addEventListener('click', addProduct)
} 

function addProduct(event) {
    let buttonClicked = event.target
    let getTitle = buttonClicked.parentElement.parentElement.parentElement.querySelector('.product-title').innerText
    let getImage = buttonClicked.parentElement.parentElement.parentElement.querySelector('.product-header img').src
    let getColor = buttonClicked.parentElement.parentElement.querySelector('.product-description-text li span').innerText
    let getSize = buttonClicked.parentElement.parentElement.querySelector('.product-description-text li select').value
    let getPrice = buttonClicked.parentElement.parentElement.querySelector('.product-description-price').innerText
    let getSpan = buttonClicked.parentElement.parentElement.querySelector('li span').getAttribute('id')

    let oldItems = JSON.parse(localStorage.getItem('newProduct')) || [];
    let newItem = {
        'title': getTitle,
        'image': getImage,
        'color': getColor,
        'size': getSize,
        'price': getPrice,
        'spanid': getSpan,
    };
    
    oldItems.push(newItem);
    localStorage.setItem('newProduct', JSON.stringify(oldItems));
}

Then, i have a code that allows me to display the data the user have locally stored by creating divs and displaying the info:然后,我有一个代码,允许我通过创建 div 并显示信息来显示用户在本地存储的数据:

let cartProducts = JSON.parse(localStorage.getItem("newProduct"))
for(let i = 0; i < cartProducts.length; i++){
    let newCartProduct = document.createElement('div')
    newCartProduct.classList.add('product')
    newCartProduct.classList.add('cart')
    const image = cartProducts[i].image
    const title = cartProducts[i].title
    const spanid = cartProducts[i].spanid
    const color = cartProducts[i].color
    const size = cartProducts[i].size
    const price = cartProducts[i].price
    let newCartProductContent = `
    <div class="product-header cart"><img src="${image}" alt="" /></div>
        <div class="product-content">
            <h3 class="product-title" id="product-title">
            ${title} 
            </h3>
            <div class="product-description">
                <ul class="product-description-text cart">
                    <li>Color: <span id="${spanid}">${color} </span></li>
                    <li>Size: ${size} </li>
                    <li>Quantity: <input type="number" class="product-description-quantity" min="1" placeholder="2" value="2"></li>
                </ul>
                <p class="product-description-price" id="price1">
                ${price} 
                </p>
                **<a href="#" class="product-description-add cart-remove">Remove<i class="fas fa-trash"></i></a>**
            </div>
        </div>`
    newCartProduct.innerHTML = newCartProductContent
    let cartItems = document.getElementsByClassName('products_container_first-row')[0]
    cartItems.append(newCartProduct)
}

So what i need to do now is to create a function that allows me to delete the data that it's the same which is on localstorage, each time that the user clicks on a "remove" button (in the above code is the line which has the ** ** at beginning and ending), but i cant figure out how to do this.所以我现在需要做的是创建一个 function 允许我删除本地存储中相同的数据,每次用户单击“删除”按钮时(在上面的代码中是具有** ** 在开头和结尾),但我不知道该怎么做。 Any ideas?有任何想法吗? Thanks!谢谢!

UPDATE: i've come to this code but i get -1 as index for each element:更新:我来到了这段代码,但我得到 -1 作为每个元素的索引:

let addCartItemButtons = document.getElementsByClassName('product-description-add')
for (let i = 0; i < addCartItemButtons.length; i++){
    let button = addCartItemButtons[i]
    button.addEventListener('click', function(event){
        let buttonClicked = event.target
        let getTitle = buttonClicked.parentElement.parentElement.parentElement.querySelector('.product-title').innerText
        let getImage = buttonClicked.parentElement.parentElement.parentElement.querySelector('.product-header img').src
        console.log(getImage)
        let getColor = buttonClicked.parentElement.parentElement.querySelector('.product-description-text li span').innerText
        let getSize = buttonClicked.parentElement.parentElement.querySelector('.product-description-text li select').value
        let getPrice = buttonClicked.parentElement.parentElement.querySelector('.product-description-price').innerText
        let getSpan = buttonClicked.parentElement.parentElement.querySelector('li span').getAttribute('id')
        console.log(getSpan)
    
        let oldItems = JSON.parse(localStorage.getItem('newProduct')) || [];
        let newItem = {
            'id': i+1,
            'title': getTitle,
            'image': getImage,
            'color': getColor,
            'size': getSize,
            'price': getPrice,
            'spanid': getSpan,
        };
        
        oldItems.push(newItem);
        localStorage.setItem('newProduct', JSON.stringify(oldItems));
    })
} 

let cartProducts = JSON.parse(localStorage.getItem("newProduct"));
for(let i = 0; i < cartProducts.length; i++){
    let newCartProduct = document.createElement('div')
    newCartProduct.classList.add('product')
    newCartProduct.classList.add('cart')
    console.log(newCartProduct)
    const id = cartProducts[i].id
    const image = cartProducts[i].image
    const title = cartProducts[i].title
    const spanid = cartProducts[i].spanid
    const color = cartProducts[i].color
    const size = cartProducts[i].size
    const price = cartProducts[i].price
    let newCartProductContent = `
    <div class="product-header cart" id="${id}"><img src="${image}" alt="" /></div>
        <div class="product-content">
            <h3 class="product-title" id="product-title">
            ${title} 
            </h3>
            <div class="product-description">
                <ul class="product-description-text cart">
                    <li>Color: <span id="${spanid}">${color} </span></li>
                    <li>Size: ${size} </li>
                    <li>Quantity: <input type="number" class="product-description-quantity" min="1" placeholder="2" value="2"></li>
                </ul>
                <p class="product-description-price">
                ${price} 
                </p>
                <a href="#" onclick="lsdel(\'newProduct\',\'+cartProducts[i].id+\');" class="product-description-add cart-remove">Remove<i class="fas fa-trash"></i></a>
            </div>
        </div>`
    newCartProduct.innerHTML = newCartProductContent
    let cartItems = document.getElementsByClassName('products_container_first-row')[0]
    cartItems.append(newCartProduct)
}
function lsdel(storage_name, value){
    if (localStorage.getItem(storage_name) === null) { 
    } else {        
        var ls_data = JSON.parse(localStorage.getItem(storage_name));
        var index   = ls_data.indexOf(value);
        console.log("selected index:"+index);
        if(index == -1){
        // if not matched selected index    
        } else {
            // is matched, remove...
            ls_data.splice(index, 1);
            localStorage.setItem(storage_name, JSON.stringify(ls_data));
            console.log(ls_data);  
        }
    }
}

value is the ID of an element, but ls_data is an array of objects, not IDs. value是元素的 ID,但ls_data是对象数组,而不是 ID。 So ls_data.indexOf(value) will not find the object in the array.所以ls_data.indexOf(value)不会在数组中找到 object。 And even if value were an object, this wouldn't work because object equality is based on identical objects in memory, not comparing contents.即使value是 object,这也不起作用,因为 object 相等是基于 memory 中的相同对象,而不是比较内容。

You need to use findIndex to match the id property of an array element.您需要使用findIndex来匹配数组元素的id属性。

 function lsdel(storage_name, value) { if (localStorage.getItem(storage_name) === null) {} else { var ls_data = JSON.parse(localStorage.getItem(storage_name)); var index = ls_data.findIndex(({id}) => id == value); console.log("selected index:" + index); if (index == -1) { // if not matched selected index } else { // is matched, remove... ls_data.splice(index, 1); localStorage.setItem(storage_name, JSON.stringify(ls_data)); console.log(ls_data); } } }

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

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