动态创建复选框单击事件选择整行,而不是仅选择jquery数据表中的复选框。这是为什么?

时间:2022-04-23 20:13:05

I have added a new row in my jquery datatable with html content(checkbox input) on some event as:

我在我的jquery数据表中添加了一个新行,其中html内容(复选框输入)在某些事件上:

$("#btn").on( 'click', function (){
    $('#mytable').DataTable().row.add([data[0],data[1],"<td><input type=\"checkbox\" value=\"\" /></td>"]).draw();
}

Now, when I click on the 'checkbox' from the dynamically created row, the whole row is getting triggered along with the checkbox. Hence, the below even is not getting triggered:

现在,当我从动态创建的行中单击“复选框”时,整个行将与复选框一起触发。因此,下面甚至没有被触发:

$('input[type=checkbox]').on( 'click', function (e){
    e.stopPropagation();
});

But in turn triggers this event:

但反过来会触发此事件:

$("#mytable tbody").on( 'click', 'tr', function (){
   $(this).addClass('selected').siblings().removeClass('selected');
 ....
}

Any idea why is this happening?

知道为什么会这样吗?

1 个解决方案

#1


1  

You can't stop propagation on a delegated event handler as it has already propagated through the DOM before it's handled.

您无法在委托事件处理程序上停止传播,因为它在处理之前已经通过DOM传播。

Alternatively you can inspect the event.target in the tr click handler and not do any work if it was the checkbox that was clicked:

或者,您可以在tr单击处理程序中检查event.target,如果是单击的复选框,则不执行任何操作:

$("#mytable tbody").on('click', 'tr', function(e) {
    if (e.target.tagName.toLowerCase() == 'input')
        return;

    $(this).addClass('selected').siblings().removeClass('selected');
})

#1


1  

You can't stop propagation on a delegated event handler as it has already propagated through the DOM before it's handled.

您无法在委托事件处理程序上停止传播,因为它在处理之前已经通过DOM传播。

Alternatively you can inspect the event.target in the tr click handler and not do any work if it was the checkbox that was clicked:

或者,您可以在tr单击处理程序中检查event.target,如果是单击的复选框,则不执行任何操作:

$("#mytable tbody").on('click', 'tr', function(e) {
    if (e.target.tagName.toLowerCase() == 'input')
        return;

    $(this).addClass('selected').siblings().removeClass('selected');
})