Having issue with click function for <tr>

Having issue with click function for <tr>

本文关键字:lt tr gt for issue with click function Having      更新时间:2023-09-26

HTML

<tr url="domain.com">
<td><input type="checkbox" name="checkbox[]" method="post" value="" class="checkbox" />  </td>
</tr>

JS

$("tr").not('.checkbox').click(function(){
    window.location = $(this).attr("url");
});

想禁用点击框内的点击功能,但上面的代码不起作用:即使我点击复选框,它也会重定向。我哪里错了?

$("tr").not('.checkbox')

此代码将匹配所有不具有checkbox类的tr元素。正如您所看到的,您的tr没有那个类,所以这个tr将匹配。

有两种基本方法可以做你想做的事情。你可以在函数中检查原始点击的元素是什么,如果它是一个复选框,就不要重定向。或者,您可以向复选框中添加一个单击处理程序并调用e.stopPropagation()

$("tr .checkbox").click(function(e){
    e.stopPropagation();
});

只需在下面的复选框中停止事件传播,

$('.checkbox').click(function(e){
   e.stopPropagation();
});

修正了打字错误。

添加一个单独的处理程序来停止传播。

$("tr").click(function(){
    window.location = $(this).attr("url");
})
  .find(".checkbox").click(function(e) { e.stopPropagation(); });

单击复选框时停止事件传播。试试这个。

$('.checkbox').click(function(e){
   e.stopPropagation();
});

并将您的代码更改为

$("tr").click(function(){
    window.location = $(this).attr("url");
});

或者,您可以检查目标并采取相应行动。试试这个。

$("tr").click(function(e){
    if(!$(e.target).is(':checkbox')){
       window.location = $(this).attr("url");
    }
});