I have the following function:
$("#example tbody").click(function(event) {
$(oTable.fnSettings().aoData).each(function (){
$(this.nTr).removeClass('row_selected');
});
$(event.target.parentNode).addClass('row_selected');
});
When a user clicks on a td element in a table it adds the row_selected class to the row. However when a user clicks on an input element inside of a td then it adds the row_selected class to the td.
Is there a way that I can change event.target.parentNode so that instead of the parent it adds the class to the parent tr?
使用closest()
。
$(event.target).closest('tr').addClass('row_selected');
Change your handler to use jQuery's event delegation instead of your own...
$("#example tbody").on("click", "tr", function(event) {
...then you can just use this
...
$(this).addClass('row_selected');
You can use parentsUntil() function, that is sort of like finding ancestors. I cant remember the function for ancestors, but this will work:
$(event.target).parentsUntil("tr").addClass('row_selected');
you can try this
$(event.target).closest('tr').addClass('row_selected');
Instead of your line
$(event.target.parentNode).addClass('row_selected');
Using closest(), you will be able to apply row_selected
class to nearest tr
element of the element you click, that may be a td
or any other element inside it.
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.