首页 > 解决方案 > 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. enter image description here

标签: javascriptloopsobjectdomlocal-storage

解决方案


您应该从 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));
            });

推荐阅读