我正在显示来自div的数据库中的数据。显示的div的数量取决于数据库记录。每个div都有一个表单,其中包含隐藏的输入和Submit按钮。当我单击Submit按钮时,我应该只从该div的隐藏输入中获取数据。问题是我仅从第一个div获取数据。HTML<div class="col-md-4 col-sm-4" th:each="product : ${products}"> <!--card --> <div class="card" style="margin-bottom: 10px;"> <span th:if="${products.empty}" style="color: #0e4377">No Products Available</span> <!-- Card image --> <div class="view overlay"> <img class="card-img-top" alt="productImage" th:attr="src=${product.image}" height="100px" width="50px" > </div> <!-- Card image --> <div class="card-body" > <!-- Title --> <h4 class="card-title" th:text="${product.name}"></h4> <!-- Text --> <span> <i class="fas fa-dollar-sign"></i> <p class="card-text" th:text="${product.price}">$</p> </span> <!--button container--> <div class="button-container" > <!-- Button --> <form action="#" th:object="${Product}" method="POST" > <input type="hidden" th:value="${product.id}" name="id" class="id"/> <input type="hidden" th:value="${product.name}" name="name" class="name"/> <input type="hidden" th:value="${product.image}" name="image" class="image"/> <input type="hidden" th:value="${product.price}" name="price" class="price"/> <input type="hidden" th:value="${session.userId}" name="userId" class="userId"/> <button type="submit" class="btn btn-info btn-sm" onclick="addToCart();">Add</button> </form> </div> <!--button container--> </div> </div>
2 回答

慕容森
TA贡献1853条经验 获得超18个赞
尝试传递关键字this
<button type="submit" class="btn btn-info btn-sm" onclick="addToCart(this);">Add</button>
和
function addToCart(this){ var id = $(this).siblings(".id").val();
添加回答
举报
0/150
提交
取消