我从我的数据库中选择了数据,然后循环显示结果以在我的页面上显示它们。我有3个结果显示。每个结果都有一个名为reduce的id按钮。单击此按钮时,应显示包含警报按钮的项目名称的警报。我正在使用jQuery来实现这一目标。
我的问题是每当我点击按钮时,只会显示结果数组中第一个项目的名称。其他两个结果中的按钮似乎不起作用。我做错了什么?
循环结果并显示数据库表中项目的代码:
if(mysqli_num_rows($run) >= 1){
while($row = mysqli_fetch_assoc($run)) {
$name = $row['name'];
$quantity = $row['quantity'];
$price = $row['price'];
$image = $row['image'];
$category = $row['category'];
$total = $price * $quantity;
echo "<div class=\"post-container\">\n";
echo "<div class=\"post-thumb\">\n";
echo "<img src='$image'>\n";
echo "</div>\n";
echo "<div class=\"post-title\">\n";
echo "<h4 style=\"font-weight:bold;\">\n";
echo "<a href=\"view.php?name=$name&category=$category\" class=\"links\" target=\"_blank\">$name</a>\n";
echo "<span id=\"deletion\">Delete</span>\n";
echo "</h4>\n";
echo "</div>\n";
echo "<div class=\"post-content\">\n";
echo "<ul style=\"list-style-type:none;\">\n";
echo "<li>Cost Per Item: <span id=\"cost\">$price</span>/=</li>\n";
echo "<li>\n";
echo "Quantity: \n";
echo "<button type=\"submit\" id=\"decrease\" class=\"glyphicon glyphicon-minus\" title=\"Decrease Quantity\"></button>\n";
echo "\n";
echo "<span id=\"cost\" class=\"quantity\"> $quantity </span>\n";
echo "\n";
echo "<button type=\"submit\" id=\"increase\" class=\"glyphicon glyphicon-plus\" title=\"Increase Quantity\"></button>\n";
echo "</li>\n";
echo "<li>Total Cost: <span id=\"cost\">$total</span>/=</li>\n";
echo "</ul>\n";
echo "</div>\n";
echo "</div>";
}
}
这是jquery:
$("#decrease").click(function(){
var name = $(this).parent("li").parent("ul").parent("div.post-content").siblings("div.post-title").find("a").text();
alert(name);
});
答案 0 :(得分:1)
您的HTML标记无效,因为只有一个元素具有给定ID - id必须是唯一的。您可以使用类,例如,类decrease
将具有选择器.decrease
,它将与您的所有按钮相关。