jQuery -当选择复选框输入或td时停止传播


jQuery - stop propogation when selecting checkbox by input or td

我想通过单击td本身(和/或复选框)来切换td内的复选框。

我有以下代码:

$("[id^=musicCheckboxHoldingTD]").on("click", function (e) {
    e.stopPropagation();
    $this = $(this);
    $this.find('.musicSelectionRoundCheckbox:checkbox').click();
});
$(".musicSelectionRoundCheckbox:checkbox").click(function(e) {
     e.stopPropagation();
     $this = $(this);
     musicCheckboxToggled($this); // this function gets called twice 
});

当我只点击td时,这个效果很好。

如果我单击td中的复选框,则由于td的事件和复选框的事件,该函数被调用两次。

我如何防止这种情况发生,只让函数运行一次?

谢谢:-)

你真的需要两个事件吗?从我所看到的,只在td上设置事件而不停止传播将允许您为复选框+ td提供处理程序。

$("#musicCheckboxHoldingTD").on("click", function (e) {
    musicCheckboxToggled($(this));
});

如果你的td有其他不应该触发事件的东西,你可以调整选择器并阻止传播。

$("#musicCheckboxHoldingTD, #musicCheckboxHoldingTD > input[type=checkbox]").on("click", function (e) {
    e.stopPropagation();
    musicCheckboxToggled($(this));
});

我对此有很多麻烦,似乎浏览器正在'检查'复选框,然后我的jquery事件正在逆转。

我最终通过将disabled="disabled"放在HTML输入元素的一行来禁用复选框。

然后我使用以下jQuery代码:
$("[id^=musicCheckboxHoldingDiv]").on("click", function (event) {
    event.stopPropagation(); // stop the event bubble up
    $this = $(this);
    var obj =$this.find('input');    
    obj.prop('checked', !obj.is(':checked'));  
    musicCheckboxToggled();    
 });

目前正在工作。如果有人看到这个答案有任何问题,请在评论中告诉我,或者用另一个答案来改进它。我把它放几天,然后把它标记为接受的答案。

感谢大家的帮助:-)