使用复选框onClick覆盖parClick上的onClick事件?

首先,抱歉我的英语不好。

我正在制作优惠券网站,但在选择和取消优惠券时遇到问题。 每张优惠券都在DIV’框中’,其中有一个复选框。

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

我知道每个人都喜欢一些代码作为例子,但问题/问题很简单,我认为你不需要在事件/函数中使用我所有无用的代码:)

谢谢 :)

如果未选中该复选框,您似乎想要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 } }); 

如果

单击处理程序看起来像这样:

 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()

你必须取消冒泡。 请看这里的解释。

您可以使用jQuery Alternative,或使用不针对您的复选框的onClicks创建子元素。 你也许可以使用这样的东西。

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

祝好运