
用 javascript 构建简易购物车
问题:如何使用 javascript 实现一个简易的购物车功能,包括以下要求?
回答:
// 获取页面元素
const leftBox = document.getElementById("left-box");
const rightBox = document.getElementById("right-box");
const addItemButton = document.getElementById("add-item-button");
// 添加点击事件处理程序
leftBox.addEventListener("click", handleLeftBoxClick);
// 添加按钮点击事件处理程序
addItemButton.addEventListener("click", handleAddItemButton);
// 处理左侧框中的点击事件
function handleLeftBoxClick(event) {
const selectedItem = event.target;
// 检查是否点击了选项
if (selectedItem.tagName !== "LI") {
return;
}
// 将选定的选项添加到右侧框
rightBox.appendChild(selectedItem.cloneNode(true));
// 从左侧框中删除选定的选项
leftBox.removeChild(selectedItem);
}
// 处理添加按钮点击事件
function handleAddItemButton() {
// 查找左侧框中选中的选项
const selectedItems = leftBox.querySelectorAll("li.selected");
// 将选定的选项添加到右侧框
for (const item of selectedItems) {
rightBox.appendChild(item.cloneNode(true));
}
// 从左侧框中删除选定的选项
for (const item of selectedItems) {
leftBox.removeChild(item);
}
}以上就是如何使用 JavaScript 实现一个简易的购物车功能?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号