【问题标题】:How to remove from list with onclick function?如何使用 onclick 功能从列表中删除?
【发布时间】:2016-11-26 04:16:45
【问题描述】:

我正在尝试创建一个函数,该函数允许我从我正在处理的网站的购物车中删除一个项目。单击以从列表中删除该特定项目并立即显示它时,我想要最后一张图像。我不想刷新页面才能看到更新。我已经尝试了我能找到的所有东西,并尝试对我的 addtocart 进行逆向工程,但我就是无法得到它。任何帮助表示赞赏!

var x = JSON.parse(sessionStorage.getItem('shoppingList'));

document.write('<table align="center" >');
    document.write('<tr>');
    document.write('<th>' + " " + '</th>');
    document.write('<th>' + "Product" + '</th>');
    document.write('<th>' + "Price" + '</th>');
    document.write('<th>' + "Quantity" + '</th>');
    document.write('<th>' + "Remove" + '</th>');
    document.write('</tr>');
        for (var i = 0; i < x.length; i++){
            document.write('<tr>');
            for(var j = 0; j < 1; j++){
                document.write('<td align="center">');
                document.write('<img src="');           
                document.write(x[i].itemImageSrc);
                document.writeln('"style="height:100px; width:150px;"/>');  
                document.write('</td>');    
                document.writeln('<td align="center">' + x[i].itemDescription + '</td>');
                document.writeln('<td align="center">' + x[i].itemPrice + '</td>');
                document.write('<td align="center">' + "1" + '</td>');
                document.write('<td align="center">');
                document.write('<img id="can_'+i+'" onclick="removeItem(i)" src="');            
                document.write("./images/Icons/garbagecan.png");
                document.writeln('"style="height:25px; width:20px;"/>');    
                document.write('</td>');
            }
            document.write('</tr>');
        }
    document.write('</table>');


function removeItem(i) {
    var list = JSON.parse(sessionStorage.getItem("shoppingList"));
    list.pop(document.getElementById("can_'+i+'"));
    //x[i] = null;
}

【问题讨论】:

  • [1] 当您清除购物车时,您正在修改一个临时变量而不是实际的会话存储,您可以通过更新会话存储来更改它。 [2] 在填充购物车时,您使用的是临时变量,因此即使会话存储值发生更改,它的值也不会更新。您将不得不为此寻找替代实现。
  • 这个'&lt;img id="can_'+i+'" onclick="removeItem(i)" src="'应该是'&lt;img id="can_'+i+'" onclick="removeItem('+i+')" src="'

标签: javascript html arrays object


【解决方案1】:

TheChetan 是对的。我需要做的是添加

sessionStorage.setItem("shoppingList", JSON.stringify(list));
    window.location.href=window.location.href

到我的 removeItem 函数结束

【讨论】:

    猜你喜欢
    • 2021-04-27
    • 2020-02-03
    • 2021-12-11
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多