2012-01-14 89 views
1

首先,对不起我的英文不好。用onClick复选框覆盖parrents onClick事件?

我在制作优惠券网站,并且无法选择和取消选择优惠券。每张优惠券都位于一个DIV“盒子”中,其中有一个复选框。

我在DIV框上做了一个onClick函数(所以用户可以通过点击DIV框内的任何东西来选择优惠券,现在我需要的是,当用户想要取消选择优惠券时(通过点击复选框在DIV框中),我需要'覆盖'DIV的onClick函数(执行onClick事件的checkbox,而不是DIV的onClick事件)

我知道每个人都喜欢一些代码作为例子,但问题/问题很简单,我不认为你需要所有的事件/功能我un'useless代码:)

谢谢:)

+2

代码样本几乎总是帮助更容易。话虽如此,你有没有考虑过在复选框上使用jQuery的stopPropagation? http://api.jquery.com/event.stopPropagation/ – j08691 2012-01-14 22:40:27

回答

2

好像你想要stopPropagation如果复选框被取消选中:http://jsfiddle.net/8Dcq8/

$("div").click(function() { 
    alert("add"); // clicking anywhere in div to add coupon 
}); 

$(":checkbox").click(function(e) { 
    if(!this.checked) { // if unchecking, remove coupon 
     alert("remove"); 
     e.stopPropagation(); // don't run parent onclick 
    } 
}); 
+1

呃,没有。 '$(this).is(“:checked”)'完全过分。 [所有你需要的是'this.checked'](http://stackoverflow.com/a/4652402/139010)。 – 2012-01-14 22:43:20

0

你必须取消冒泡。有关说明,请参阅here

1

如果<div>单击处理看起来是这样的:

var $boxes = $('div.box'); 
$boxes.on('click', function() 
{ 
    // do whatever to select the coupon 
}); 

然后复选框处理程序应该是这个样子:

$boxes.find('input[type="checkbox"]').on('click', function (event) 
{ 
    event.stopPropagation(); 
    // do whatever to deselect the coupon 
}); 

event.stopPropagation()

0

您可以使用jQuery替代方法,或者使用onClicks创建子元素,这些子元素不会针对您的复选框。你也许可以使用类似的东西。

document.getElementById('element').checked.onreadystatechange=function(){ 
//code 

} 

好运