如何使用相同的类选择元素并使用JS添加到我的购物车中

问题描述 投票:0回答:1

我想要一个函数,该函数通过单击添加到购物车按钮来选择产品的图像,描述和价格,并对每个元素使用相同的类,然后将其添加到购物车。我是编程和这个平台的新手。让我知道是否需要更具体说明。

这里是一些代码,是一些HTML代码。谢谢。

<div id="myModal" class="modal">

  <!-- Modal content -->
  <div class="modal-content">
    <span class="close">&times;</span>
    <p><h3 align="center">My Cart</h3></p>
    <form>

    <table class="table">

      <thead>
        <tr>
          <th>Product</th>
          <th>Description</th>
          <th>Price</th>
          <th>Quantity</th>
          <th>Total</th>

        </tr>
      </thead>

        <tbody id="list">



      </tbody>


        </table>
      </form>

        </div>

      </div>
        <tr>
              <td align="center">
                <img src="Images/1.jpg"  class="thumbnail" onclick="setitem()">
                <p class="description">Grow Through What You Go Through</p>
                <p class= "price">$ 29.95 USD</p>
                <p><a class="add btn cart px-auto">ADD TO CART</a>
                </p>


              </td>


              <tr>
              <td align="center">
                <img src="Images/34.jpg"  class="thumbnail">
                <p class="description">Fight</p>
                <p class= "price">$ 29.95 USD</p>
                <p><a class="add btn cart px-auto">ADD TO CART</a>
                </p>


              </td>

不确定我在用JS做什么,因为我需要使用本地存储来实现购物车。这里是一些JS:

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks the button, open the modal 
btn.onclick = function() {
  modal.style.display = "block";
}

// When the user clicks on <span> (x), close the modal
span.onclick = function() {
  modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}

     function setitem() {
    localStorage.setItem('image', document.getElementById('image').value);
    localStorage.setItem('description', document.getElementById('desc').value);
    addtoCart();

}


function addtoCart() {
    var currentimage = localStorage.getItem('image');
    var currentdesc  = localStorage.getItem('desc');

    document.getElementById('list').innerHTML =  currentimage + currentdesc;


}
javascript loops local-storage cart shopping-cart
1个回答
0
投票

您可以通过单击锚点来获得按钮的父元素:

$('a').click(function(){
  var parentElement = $(".cart").closest("td");
}); 

现在parentElement为<td>,并且<td>具有您需要的所有项目(图像,描述,价格)。

© www.soinside.com 2019 - 2024. All rights reserved.