简体   繁体   中英

jQuery: Whole table row highlight except when certain child elements are clicked

My question is how do I make a parent clickable using jQuery, but exclude certain child elements (eg: checkbox or a hyperlink) from being clicked? And at the same time, I want to allow the child elements to be clicked themselves (eg: the hyperlink needs to work?

To elaborate, when a row inside a table is clicked, I want it to add a checked class to the row to highlight it.

I have a checkbox within each row that toggles the checked class already. So I plan to use trigger() to click this checkbox when the row is clicked. You'll see in my JSFiddle example .

The problem I am having is if they click the checkbox itself or a hyperlink within the row, I don't want it to trigger the click.

I was hoping using a selector such as $('td :not(a,input)') would work but obviously I don't understand clicking child elements properly as this does not work.

In my same JSFiddle example you'll notice in the default example if you click the checkbox

I've been browsing the web for an answer but no one seems to be doing exactly what I'm trying to achieve.

You could probably replace this:

$('td :not(a,button,.custom-checkbox)').on('click', function() {
    $(this).closest('tr').find('input').trigger('click');
});

For this

$('td').on('click', function(e) {
  var $target = $(e.target); //This will get the element that is actually being clicked      
  if (!$target.is("a,button,.custom-checkbox, [type=checkbox]")) {
    //If the element being clicked doesn't belong to the group of the "unclickable" elements
    //I also added checkboxes to the "unclickable" elements
    $(this).closest('tr').find('input').trigger('click');
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM