javascript - i am generating a dropdown menu using the DOM and filling the options with data received from an API
问题描述
I want to be able to loop through each of my dynamically generated options (see left hand side of pic) and add the code below so that I can keep clicking 'add to cart' and it updates the number in each which gets saved to localStorage. At the moment the code below just keeps adding 1 to 'num'. So when I change the dropdown option the 'optionQuanity' value continues where the last value left off. However, I want each dropdown option to have its own 'num' and to be able to switch back and forth between the options and keep adding to the cart. I've added a picture at the end so you can see what I mean. Thank you for your help!!!!
let num = 0
const addToCart = document.getElementById('addToCart')
addToCart.addEventListener('click', function(option) {
option.preventDefault();
let cartObject = {
name: jsonResponse.name,
price: jsonResponse.price,
option: select.value,
optionQuantity: num
}
num++
localStorage.setItem(select.value, JSON.stringify(cartObject));
});
Below you can see the option choices to the left (there are a different quantity of options depending on which API I return - it needs to remain dynamic). On the right you can see how I have converted the object to localStorage and I would like to be able to keep adding to 'optionQuantity' depending on which option I select.
解决方案
您应该从 localStorage 中检索选定的选项,并在内部操作“num”,而不共享 var num 的范围。
像这样的东西:
//let num = 0 //delete this
const addToCart = document.getElementById('addToCart')
addToCart.addEventListener('click', function(option) {
option.preventDefault();
let selectedItem = JSON.parse(localStorage.getItem(select.value));
//declare num here
let num = 0;
if (selectedItem) {
num = selectedItem.num+1;
}
let cartObject = {
name: jsonResponse.name,
price: jsonResponse.price,
option: select.value,
optionQuantity: selectedItem.num+1;
}
localStorage.setItem(select.value, JSON.stringify(cartObject));
});
推荐阅读
- javascript - app.use(express.static()) 在程序结束时
- django - Django manage.py - 区分 runserver 和/或从其他命令上下文运行的实际服务器?
- python - 从 Google OAuth2 为自定义 Django 用户模型提取配置文件数据
- c++ - 将 Glib 主循环集成到 libev 事件循环中(C++)
- sql - SQL:确定在位置花费的时间(雪花)
- c - 如何评估带有文字后缀 ULF 的 C 表达式?
- vega-lite - 转换 Vega 数据集以计算和使用最小/最大范围
- python - 错误:将 Django 应用程序部署到 Heroku 推送被拒绝
- reactjs - 构建失败 - 在 AWS Amplify 中“npm build”后检测到非零退出代码
- python - 创建具有混合数据类型的结构化数组,但不能创建布尔类型