最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I select an element's parent row in a table? - Stack Overflow

programmeradmin2浏览0评论

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?

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?

Share Improve this question edited Jul 22, 2012 at 18:22 Lee Taylor 7,98416 gold badges37 silver badges53 bronze badges asked Jul 22, 2012 at 18:16 user1464139user1464139
Add a ment  | 

4 Answers 4

Reset to default 7

Use 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.

发布评论

评论列表(0)

  1. 暂无评论