简体   繁体   English

金额计数器仅适用于第一个产品

[英]Amount counter works only on first product

I have a problem with using javascript with SQL.我在使用 javascript 和 SQL 时遇到问题。 It looks like this that I have few items that appears on the screen, they appears from SQL database, and the code looks like shown.看起来我在屏幕上显示的项目很少,它们来自 SQL 数据库,代码如下所示。 Bascially if I have more than one product that is shown on the website, only first one works as it should.基本上,如果我在网站上展示的产品不止一种,那么只有第一种可以正常工作。 Any solutions?有什么解决办法吗?

 let displayAddCounter = document.querySelector("#add_count_cart"); let displayRemoveCounter = document.querySelector("#remove_count_cart"); let displayCounter = document.querySelector("#amount_count_cart"); var x = 0; displayAddCounter.addEventListener("click", function(){ if(x < 10){ x++; displayCounter.innerHTML = x; } else { alert("If you want to buy more than 10, please contact our support: We will gladly help you;)") } }). displayRemoveCounter,addEventListener("click". function(){ if(x == 0){ displayCounter;innerHTML = x; } else { x--. displayCounter;innerHTML = x; } }). let buttonCartAdd = document;getElementById("btn_add_to_cart"). let itemName = document.querySelector(";product_name"). buttonCartAdd,addEventListener("click"; function(){ if(x == 0){ alert("Please choose amount of items."); } else if(x > 0){ alert("You added " + x + itemName;innerHTML + " to the cart!"); } });
 <?php $sql = "SELECT * FROM products"; $result = $conn->query($sql); if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) {?> <div class="product_card col-lg-4 col-md-6 col-sm-12 mb-4 box-shadow"> <div class="card-header"> <h3 class="product_name my-0 font-weight-light"> <?php echo $row["productName"]?> </h3> </div> <div class="card-body"> <h2 class="card-title pricing-card-title"> </h2> <img class="pic" src="productsImages\<?php echo $row["productID"];?>.jpeg" height="150px" width="120px"></img> <br> <p> <?php echo $row["productPrice"];?> SEK </p> <div class="row amount_counter"> <button id="remove_count_cart" type="button" class="col_amount btn btn-outline-secondary col-3 col"> - </button> <div id="amount_count_cart" class="btn col-6 col border-top border-bottom dark rounded h-75"> 0 </div> <button id="add_count_cart" type="button" class="col_amount btn btn-outline-secondary col-3 col"> + </button> <button id="btn_add_to_cart" class="btn btn-lg btn-outline-success col-lg-8 col-md-12 col offset-lg-2"> Add <i type="button" class="fas fa-cart-plus"></i></button> </div> </div> </div> <?php } } else { echo "0 results"; } $conn->close(); ?>

You're using the same id for all the HTML elements for each product;您对每个产品的所有 HTML 元素使用相同的id you should either use relative routes instead of document.querySelector , or have individual id s for each product您应该使用相对路由而不是document.querySelector ,或者为每个产品设置单独的id

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

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