在使用jquery .context和.index时遇到麻烦


having trouble with jquery .context and .index

下面是生成动态产品表的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教程,但没有幸运地找到一个方法。

谢谢

而不是有一个addBuyButton为每个项目的jQuery,我将只有一个事件监听器,处理所有这样(我个人不喜欢大块的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中获取产品的值并将其添加到购物车中。

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