将项目从一个 html 页面移动到另一个

问题描述 投票:0回答:1

如何在不使用或使用 localStorage.set-getItem 的情况下将列表中的项目从一个 html 页面移动到另一个

我正在制作一个电子商务网站。当我的客户单击某个项目的“添加”按钮时,我希望将该项目移至购物车。问题是购物车是不同的html页面(不在同一个maine html页面)

我试过这个,但是没有用

Let list = document.querySelectorAll(".list .item")
    list.forEach(item => { item.addEventListener("click", function(item) { if(event.target.classList.contains("add")) {
document.querySelector(".listcart").appendChild(item)
   }
  })
})

(列表在主html页面,listcart在另一个html页面) 当我将 listcart 放在同一个主页时它起作用了,但是当我将它移到另一个主页时,代码停止工作,但控制台中没有错误

伙计们,你们对此有解决方案吗?

javascript html function frontend shopping-cart
1个回答
0
投票

由于您正在尝试制作购物车,因此不使用任何 Javascript 框架的最佳做法是使用本地存储。

但是,如果您仍然想在不使用本地存储的情况下执行此操作,则可以在用户单击“添加”按钮时将商品 ID 作为 URL 参数传递,并使用 JavaScript 在购物车页面上检索商品数据。例如,您可以使用类似 cart.html?item=123 的 URL 将用户重定向到购物车页面,其中 123 是所选商品的 ID。在购物车页面,可以使用JavaScript从URL中获取item参数,显示对应的item。

在源页面

// Assume we have a list of items with IDs and names
let items = [
  { id: 1, name: "Item 1" },
  { id: 2, name: "Item 2" },
  { id: 3, name: "Item 3" }
];

let list = document.querySelectorAll(".list .item");
list.forEach(item => {
  item.addEventListener("click", function(event) {
    if (event.target.classList.contains("add")) {
      // Get the item ID from the data-id attribute
      let itemId = event.target.parentElement.dataset.id;
      // Redirect the user to the shopping cart page with the item ID as a parameter
      window.location.href = `cart.html?item=${itemId}`;
    }
  });
});

在购物车页面。

// Retrieve the item ID from the URL parameter
let urlParams = new URLSearchParams(window.location.search);
let itemId = urlParams.get("item");

// Find the item with the matching ID
let selectedItem = items.find(item => item.id == itemId);

// Display the selected item in the shopping cart
let cartList = document.querySelector(".listcart");
let cartItem = document.createElement("div");
cartItem.classList.add("item");
cartItem.dataset.id = selectedItem.id;
cartItem.innerHTML = `<span>${selectedItem.name}</span>`;
cartList.appendChild(cartItem);

© www.soinside.com 2019 - 2024. All rights reserved.