簡體   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