Click event on table row - only trigger if nothing else is 'clicked'

放肆的年华 提交于 2019-12-22 03:22:22

问题


I'm having some issues with some jQuery code, and I'm hoping and thinking that the solution is relatively simple.

Say I have a table like:

<table>
   <tr>
     <td><input type="checkbox" name="hai" value="der" /></td>
     <td><a href="mypage.php">My link</a></td>
     <td>Some data</td>
     <td>Some more data</td>
   </tr>
   ...
</table>

Now through JavaScript I do the following in jQuery(document).ready();

jQuery("table tr").click(function(){
   var row = jQuery(this);
   var hasClass = row.hasClass("highlight");
   jQuery("table tr").removeClass("highlight");
   if(!hasClass){
     row.addClass("highlight");
   }
});

All of this is pretty simple stuff - I want to be able to click a row and have it being highlighted and only one row can be highlighted at a time (obviously in my actual code I do more than that) - now here's my problem:

When a user clicks the anchor tag, or the checkboxes, this triggers the row click event as well and I cannot work out how to filter that out? I know I need to include the event in my click handler, but how to check for this in a such way that it works in as many browsers as possible?


回答1:


Try adding handlers to the other elements that respond to click events and stop the event from bubbling up. This would be in addition to what you already have.

jQuery('table input, table a').click( function(e) {
    e.stopPropagation();
    return true;
}):



回答2:


$("table tr").click(function(event){
   if (event.currentTarget.tagName != "TR") { return; }

   $(this).closest("table").find("tr.highlight").removeClass("highlight");
   $(this).addClass("highlight");
});



回答3:


$("table tr").click(function(e){

if (e.target instanceof HTMLInputElement || e.target instanceof HTMLAnchorElement){
return;
}
var row=$(this);
$('table tr').removeClass('highlight');
row.addClass('highlight','normal');

})


来源:https://stackoverflow.com/questions/877351/click-event-on-table-row-only-trigger-if-nothing-else-is-clicked

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!