我从mysql数据库中检索了记录,并使用循环将其显示在我的页面中。在页面上显示的每个记录中(我有4个),有一个按钮和一个span元素,其中包括“减少”和“数量”类等。当我单击减少按钮时,它使用ajax将数据库上的“数量”减少1,然后返回我想在“数量”span元素中显示为文本的新值。现在我已经能够将所有这些工作除了在一个区域之外。返回新数量后,它会更改显示的所有记录的“数量”值,而不是与单击的按钮位于同一容器中的值。任何人都可以告诉我我的编码出错了。
以下是显示数据的代码的摘录:
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\" class=\"glyphicon glyphicon-minus decrease\" title=\"Decrease Quantity\"></button>\n";
echo "\n";
echo "<span id=\"cost\" class=\"quantity\"> $quantity </span>\n";
echo "\n";
echo "<button type=\"submit\" class=\"glyphicon glyphicon-plus increase\" 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 itemName = $(this).parent("li").parent("ul").parent("div.post-content").siblings("div.post-title").find("a").text();
$.post(
"decrease-cart.php?username=<?php echo $username?>",
{name: itemName},
function(result){
$(this).siblings(".quantity").text(result);
}
);
});
答案 0 :(得分:0)
我看到你试图在ajax回调中使用$(this)
$.post(
"decrease-cart.php?username=<?php echo $username?>",
{name: itemName},
function(result){
$(this).siblings(".quantity").text(result);
}
);
我不应该直接使用$(this)
这样做,将您选择的节点存储在临时变量
中$(".decrease").click(function(){
var __temp = $(this);
var itemName = __temp.parent("li").parent("ul").parent("div.post-content").siblings("div.post-title").find("a").text();
$.post(
"decrease-cart.php?username=<?php echo $username?>",
{name: itemName},
function(result){
__temp.siblings(".quantity").text(result);
}
);
});