繁体   English   中英

如何使用 JavaScript 从 div 中提取数据,并显示在同一页面内的其他 div 中(引导模式)

[英]How to extract data from div, and display in other div within same page (bootstrap modal) using JavaScript

我尝试通过 ids 获取数据,然后添加到本地存储,但是如何在模式内的不同 div 中显示获取的数据。 (没有显示模态的代码)

代码:

 var cart = []; function addItem(id) { var product = document.getElementById(`product-${id}`).innerHTML; var price = document.getElementById(`price-${id}`).innerHTML; var img = document.getElementById(`image-${id}`).getAttribute('src'); let item = [product,price,img] cart.push(item); localStorage.setItem('cart', JSON.stringify(cart)); var content = document.getElementById('products') content.innerHTML = localStorage.getItem('cart') }
 <div class="product-box"> <p class="productbadge">10% Off</p> <img id="image-1" src="flower1.jpg" height="250px" width="220px"> <br> <div class="productsumm" id="product-1">Red Roses</div> <p class="productprice" id="price-1">Rs. 300</p> <a class="productbuy" onclick="addItem('1');" align="right" data-toggle="modal" data-target="#basicModal">Add to Cart</a> </div>

看起来您正在尝试将数组显示为内容。

您需要使用forEach循环遍历内容数组并分别显示每个项目。 在这种情况下,您不需要购物车数组。 此外,当您JSON.stringify数据时,您需要JSON.parse检索它时。

 function addItem(id) { var product = document.getElementById(`product-${id}`).innerHTML; var price = document.getElementById(`price-${id}`).innerHTML; var img = document.getElementById(`image-${id}`).getAttribute('src'); let item = [] item.push(product, price, img); localStorage.setItem('item', JSON.stringify(item)); var content = document.getElementById('products') var itemArray = JSON.parse(localStroage.getItem('item') //Then Loop through the itemArray to display content

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM