开发者

Getting a parent element for a jquery selector

I have a table where each row has a CSS id like this:

<table>
<tr id='1'>...</tr>
<tr id='2'>...</tr>
<tr id='3'>...</tr>
</table>

In a row, a user can click on a particular element within a cell. I want to find the row that has been clicked on.

So for example:

<tr id='x'><td></td>...<td><div class='someclass'><div class='anotherclass'></div></div></td开发者_开发问答>...</tr>

In this case, I want to respond when the user clicks on a class='anotherclass' element. I want to get the id of the row containing this clicked element but I don't want to use $(this).parent().parent().parent().... etc. because there are multiple levels of parentage and it gets ugly.

Is there a way to get the row containing this element with using .parent() multiple times?

UPDATE: Thanks everyone. That is perfect.


Use closest():

$('.anotherclass').click(function () {
     alert($(this).closest('tr').prop('id'));
});


Use closest:

$(".anotherclass").click(function() {
    console.log($(this).closest("tr").attr("id"));
});

From the docs:

Get the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.


you can use this.

$('.anotherclass').click(function () {
     alert($(this).parents('tr').attr("id"));
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜