我是Javascript/Jquery的新手,目前正在撰写一个网上购物网站作为练习。我想编写一个函数,这样每当我点击的形象“buy_btn.jpg”,项目在购物车的数量将增加1在jQuery中可以点击()用于<img>吗?
增加这里是我的js代码:
$('img[alt="buy"]').click(function(){
var item_bought = $(".shopNum").val();
item_bought++;
$(".shopNum").html(item_bought);
})
这里是我的按钮和购物车数量的html代码:
<div class = "topr_bot">
<div class = "topr_bot_left">
<img src = "image/buy_btn.jpg" alt="buy"> //this is the "add to
<p>Attention: This item will ONLY provide a normal receipt</p>
</div>
<div class = "topr_bot_right">
<img src = "image/buy_btn.jpg" alt="buy2">
</div>
</div>
<div class="shopCar fr">
<span class="shopText fl">Shopping Cart</span>
<span class="shopNum fl">0</span>
</div>
的问题是,我试图通过它的ALT标签来获取图像,并使用警报和console.info()
调试它,但没有弹出/出现。是因为我用错误的方式来获取图像,或者因为我不应该把click()
放在img
上?
谢谢。
你为什么不只是添加一个id到该图像,选择这种方式? –
如果您对HTML有任何控制,请在图像中添加一个类或ID。不要使用alt属性来选择图像。 – JJJ
似乎代码是正确的,我正在使用'.html()'输入类'shopNum'的文本。 –