我有一个div,我希望div在点击时转到一个链接。但是,在div中,我还有一个链接,我只想将它添加到购物车(通过ajax),但不要去链接。
PARENT ELEMENT JS for LINK
$(document).on("click", '.product_result', function(){
url = $('h3 a',this).attr('href');
window.location = url;
});
加入购物车的儿童元素
$('.product_add').click(function(e){
e.preventDefault();
var pid = $(this).siblings('.product_pid').val();
var quantity = $(this).siblings('.product_cart input').val();
var product_name = $(this).siblings('.product_name_add').val();
add_cart(pid,quantity);
cart_status(quantity,product_name);
});
HTML
<div class="product_result_wrapper">
<div class="product_result">
<div class="result_image"><img height="100" width="150" alt="Product NAme" src="image.jpg"/></div>
<div class="product_info">
<h3><a href="link" title="image">Product Name</a></h3>
<p class="product_info_desc">CONTENT</p>
<div class="product_price"><span>Price:</span>£495.00</div>
<div class="product_more_info"><a href="link">More Info</a></div>
<div class="clr"></div>
</div>
<div class="clr"></div>
<div class="product_order">
<div class="product_cart">
<input type="text" value="1"/>
<input class="product_pid" type="hidden" value="44"/>
<input class="product_name_add" type="hidden" value="product_id"/>
<input class="product_add" type="button" value="Add to Cart"/>
</div>
</div>
</div>
</div>
所以问题是.product_adult元素中的.product_add元素。我通过创建一个额外的父元素.product_result_wrapper来攻击它,并将add_cart元素放在那里(未在此代码中显示),只是将元素的位置更改为出现在.product_result元素中。
我也尝试过使用CSS,使其成为一个更高的z-index,具有相对位置,但这也不起作用。
那么如何防止js事件的默认?因此,我可以在此元素中包含与同一事件不同的元素,但要执行不同的操作吗?
答案 0 :(得分:1)
将e.preventDefault();
功能中的$('.product_add').click(function(e){})
更改为e.stopImmediatePropagation();
必须阻止触发.product-result点击侦听器
答案 1 :(得分:0)
听起来你正在寻找e.stopPropagation()
,而不是e.preventDefault()
。然而,使用其中任何一个总是很麻烦。如果可能的话,最干净的解决方案是更具体地说明触发“父元素链接”的内容,例如:而不是
$(document).on("click", '.product_result', function(){
...
类似
$(document).on("click", '.product_result h3 a', function(){
var url = $(this).attr('href');
...
同样,我不知道你是否可以这样做,但是你可以玩JSFiddle。