ajax不适用于项目列表,但适用于列表的第一项

时间:2016-12-26 22:01:16

标签: javascript jquery ajax

我正在使用产品列表,我想在购物车中添加产品。但不幸的是,ajax代码仅适用于列表中的第一项。或者如果我转到页面包含单个产品的详细信息页面,则代码可以正常工作。请告诉我我做错了什么。

    $(document).ready(function(){
        $("#addToCart").click(function(){
            var productId  = $("#productId").val(); 

            $.ajax({
                url:'<?php echo site_url('cart/addToCart/'); ?>',
                data:{productId:productId},
                type:'POST',
                success:function(data){
                    // Change css value of "result" div and Display
                    $("#result2").css("display", "block");
                    $("#result2").html(data);
                }
            });
        });
    });
<div class="icon">
<input type="hidden" id="productId" value="<?php echo $product->productId; ?>">
<a href="#" id="addToCart"><span class="glyphicon glyphicon-shopping-cart"></span></a>
<span class="glyphicon glyphicon-copy"></span>
</div>

2 个答案:

答案 0 :(得分:3)

您使用id定位addToCart按钮,而id只能用于页面上的单个元素。在包含多个产品的网页上,这意味着有多个元素使用addToCart id

addToCart id更改为类,然后相应地更改选择器(即$(.addToCart))。

答案 1 :(得分:1)

您不能拥有多个具有相同ID的元素。在您的情况下,addToCartproductId都具有相同的ID。

我修改了下面的代码,以便它可以用于页面上列出的任意数量的产品。它可以通过查找作为产品ID的sibling元素来执行此操作:

&#13;
&#13;
    // no-conflict safe "shorthand" document ready
    jQuery(function($) {
        // Access the button by class
        $(".addToCart").click(function() {
            // Find the sibling with the class productId
            var productId  = $(this).siblings(".productId").val(); 

            $.ajax({
                url:'<?php echo site_url('cart/addToCart/'); ?>',
                data:{productId:productId},
                type:'POST',
                success:function(data) {
                    // Change css value of "result" div and Display
                    $("#result2").css("display", "block");
                    $("#result2").html(data);
                }
            });
        });
    });
&#13;
<div class="icon">
<input type="hidden" class="productId" value="<?php echo $product->productId; ?>">
<a href="#" class="addToCart"><span class="glyphicon glyphicon-shopping-cart"></span></a>
<span class="glyphicon glyphicon-copy"></span>
</div>
&#13;
&#13;
&#13;