【问题标题】:Remove Item from array in Local storage using jQuery使用 jQuery 从本地存储中的数组中删除项目
【发布时间】:2017-05-23 22:25:47
【问题描述】:

概述:基于前端的愿望清单

技术: HTML5 (localStorage)、CSS 和 jQuery

功能:添加项目,重新加载前删除项目,实时计数

问题:如果我添加产品,重新加载并尝试将其从阵列中删除,它将无法正常工作。

我不确定如何解决问题的代码:

$("#wish_list_item").on("click", ".w-premove", function() {
$product_id = $(this).attr("wpid");
$("#list_id_" + $product_id).remove();
wish_list = $.grep(wish_list, function(n, i) {
  return n != $product_id;
});
localStorage.setItem(wishlistkey, JSON.stringify(wish_list));
show_message("Product removed");
count_items_in_wishlist_update();
});
});

链接到我的小提琴: https://jsfiddle.net/3ybwf3c3/4/

解决方案: https://jsfiddle.net/3ybwf3c3/6/

代码:

$("tr.wishlist-item").each(function(index, el) { wish_list.push(el.outerHTML); });

【问题讨论】:

  • 请在问题本身中包含minimal reproducible example。当前的代码同时是太多的代码和太少的代码;我们希望看到代码工作的 HTML,但我怀疑我们是否需要所有这些 JavaScript。请尝试将代码减少到重新创建错误所需的最低限度。
  • @MikeMcCaughan 我已经减少了 JS 并且仍然提供了指向小提琴的链接。希望这会有所帮助。
  • 点击“运行代码sn-p”按钮。你看到结果了吗?不?那么它是不完整的,或可验证的。这样想;您要求某人调试您的代码。你会给那个人所有需要的代码来帮助你解决你的问题吗?或者你会给那个人一些甚至不会运行的代码?
  • @MikeMcCaughan 道歉,不知道为什么我的 JSFIddle 链接没有出现。由于此处的代码编辑器在沙箱中运行,因此我已使用链接更新票证

标签: javascript jquery css html local-storage


【解决方案1】:

问题就在这里:

wish_list = $.grep(wish_list, function (n, i) {
    return n != $product_id;
});

n 包含整个 tr 元素的 HTML 字符串,但 $product_id 只是一个字符串 ID。所以一切都匹配,然后您将所有行放回本地存储。

由于您从 DOM 中删除了产品,您只需重新查询 DOM 以获取新的 HTML 字符串:

wish_list = [];

$("tr.wishlist-item").each(function(index, el) { 
    wish_list.push(el.outerHTML);
});

【讨论】:

    猜你喜欢
    • 2016-12-09
    • 2019-11-26
    • 1970-01-01
    • 2021-09-02
    • 2018-11-12
    • 2023-03-10
    • 1970-01-01
    • 2016-03-31
    • 1970-01-01
    相关资源
    最近更新 更多