1

这是我生成动态产品表的 PHP 代码:

while($item = mysqli_fetch_array($result))
            {
enter code here

$i++;
$pic = "cartimg/".$item[2];
  echo "<div class='prod_box'".$i.">
    <div class='center_prod_box'>
      <div class='product_title'><a>".$item[1]."</a></div>
      <div class='product_img'><a ><img src='".$pic."' alt='' border='0' /></a></div>
      <div class='prod_price'><span class='reduce'>".$item[3]."$</span> <a class='price'>".$item[4]."$</a></div>
    </div>
    <div class='prod_details_tab'> <a class='prod_buy'>Add to Cart</a> <a  class='prod_details'>Details</a> </div>
  </div>";
            }
  ?>

这是我的 jQuery 响应单击事件以将产品添加到购物车

enter code here
cart.addBuyButton(".prod_buy",{

            name:'MacBook',                     // Item name appear on the cart
            thumbnail:'media/macbook.jpg',      // Thumbnail path of the item (Optional)
            price:$("span").index(0),                        // Cost of the item
            shipping:20   
                                  // Shipping cost for the item (Optional)
        });
  prettyPrint();

这是 addBuyButton 函数的查询

 enter code here
 self.addBuyButton=function(target,data){$(target).click(function(){self.cart.add(data)

问题是,我将有 10 个容器,包含 10 个产品,具有相同的类名和 Id 名称,如果客户点击,我不知道如何读取“.$item[4].”$ 的数量添加到不同产品的购物车。

现在函数插入 12 作为价格。

请帮帮我,我浏览了许多 jQuery 教程,但没有找到方法。

谢谢

4

1 回答 1

0

我不会为 jQuery 上的每个项目都添加一个 addBuyButton,而是只有一个事件侦听器可以像这样处理所有事件(我个人不喜欢引号中的大块 php,因为我的 IDE 没有颜色突出显示所以请原谅我的 php语法。不喜欢的可以不用照着做):

PHP

<div id="products">
<?php while ($item = mysqli_fetch_array($result)) : ?>

     <!-- additional code here -->

    <div class="product prod_box<?php echo ++i; ?>">
        <div class="center_prod_box">
            <div class="product_title"><?php echo $item[1] ?></div>
            <div class="product_img"><img src="cartimg/<?php echo $item[2] ?>" border="0" /></div>
            <div class="prod_price">
                <span class="reduce"><?php echo $item[3] ?>$</span> 
                <a class="price"><?php echo $item[4] ?>$</a>
            </div>
        </div>
        <div class="prod_details_tab"> 
            <a class="prod_buy">Add to Cart</a> 
            <a class="prod_details">Details</a> 
        </div>
    </div>
<?php endwhile; ?>
</div>

JAVASCRIPT

$('#products').on('click', '.prod_buy', function() {
    var product = $(this).closest('.product');

    cart.add({
        name: product.find('.product_title').first().text(),
        thumbnail: product.find('.product_img').first().text(),
        price: product.find('.price').first().text(),
        shipping: 20 
    });
});

因此,这是您所有 prod_buy 按钮的一个事件侦听器,它从 DOM 中获取产品的值并将其添加到购物车中。

如果您需要任何进一步的帮助,请在这篇文章中添加评论,我会在我的答案中添加更多内容。

于 2013-06-09T05:02:06.347 回答