2

我有一个小问题,基本上我有一个隐藏的输入按钮,它加载了数据库表中的唯一值:<input type="hidden" name="ProductId" class="ProductId" value='.$row["ProductId"].' />这个按钮会根据通过此方法返回的行数重复:

while ($row = $result->fetch()) {
    echo '<table class="cart-row" cellspacing="0" cellpadding="0" width="100%">';
    echo '<tbody>';
    echo '<tr>';
    echo '<td width="75"><img border="0" width="59px" height="78px" title="" alt="" src=' . $row["ImagePath"] .'></td>';
    echo '<td width="203"><span class="itemElements itemName">'. $row["Name"] .'</span></td>';
    echo '<td width="203"><input type="submit" class="btnMinus linkbtnType2" value="-"><input type="submit" class="btnPlus linkbtnType2" value="+"></td>';
    echo '<td width="135"><span class="qtyNum">('. $row["Qty"] .')</span> <br />';
    echo '<input type="hidden" name="ProductId" class="ProductId" value='.$row["ProductId"].' />';
    echo '<span class="qtyRemoveLink"><input type="submit" class="btnRemove linkbtn" value="Remove"></td>';                            
    echo '<td width="180"><span class="itemElements orderStatus">In Stock Usually dispatched within 24 hours</span></td>';
    echo '<td width="175" class="itemPriceRow"><span id="itemPrice">€ '. $row["Price"] .'</span></td>';
    echo '</tr>';
    echo '</tbody>';
    echo '</table>';
    echo '<br>';                            
}  

我使用 jQuery 方法从隐藏按钮中读取此值,但它仅从生成的第一个输入按钮中读取值。我尝试将按钮从 ID 更改为类,但没有运气。

这是 jQuery 方法:

$('.btnRemove').click(function() {
    var productId = $(".ProductId").val();
    $.ajax({
        type: "POST",
        url: "functions/deleteCartItem.php",
        data: "productId="+productId+ "",
        success: function(msg){   
            alert(msg);
        }
    })
})

我能想到的一个可能的解决方案是为id每个按钮添加一个唯一的,这样它们不仅可以通过名称来识别,还可以通过id. 但是,这会在从 jQuery 方法中读取它时产生问题。

有任何想法吗?

4

4 回答 4

1

尝试 :

var productId = $(this).closest('tr').find(".ProductId").val();

this称为$('.btnRemove')DOM 元素。

jQuery(this).closest("tr")我们沿着 DOM 树向上搜索第一个tr元素。

从这里我们搜索.ProductId.

安德烈亚斯

于 2011-12-22T09:21:03.603 回答
1

您的假设是正确的,因为您正在按导致问题的类引用。您将返回一个包含所有元素var productId = $(".ProductId").val();的数组,并且只返回其中第一个元素的值。.ProductIdval()

要解决此问题,您需要获取与导致单击事件的元素.ProductId位于同一容器中的.btnRemove元素,如下所示:

$('.btnRemove').click(function() {
    var productId = $(this).closest("td").find(".ProductId").val(); // amended selector
    $.ajax({
        type: "POST",
        url: "functions/deleteCartItem.php",
        data: "productId="+productId+ "",
        success: function(msg){   
            alert(msg);
        }
    })
})
于 2011-12-22T09:23:32.290 回答
1

它不会返回正确的值,尝试类似

var productId = $(this).parent().find(".ProductId").val();

或者

var productId = $(this).parent().children(".ProductId").val();

或者

var productId = $(this).prev(".ProductId").val();

或者

var productId = $(this).siblings(".ProductId").val();

小提琴:http: //jsfiddle.net/fwM3T/

于 2011-12-22T09:25:06.560 回答
0

你应该试试:

 var productId = $(this).closest('tr').find("input[name=ProductId]").val();
于 2011-12-22T09:24:43.050 回答