获取jQuery选择器的父元素 [英] Getting a parent element for a jquery selector

查看:199
本文介绍了获取jQuery选择器的父元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表,其中每一行都有这样的CSS ID:

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.

例如:

<tr id='x'><td></td>...<td><div class='someclass'><div class='anotherclass'></div></div></td>...</tr>

在这种情况下,我想在用户单击class ='anotherclass'元素时做出响应.我想获取包含此clicked元素的行的ID,但是我不想使用$(this..parent().parent().parent()....等),因为存在多个级别的亲子关系它变得丑陋.

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.

是否可以通过多次使用.parent()获取包含此元素的行?

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

更新:谢谢大家.太完美了.

UPDATE: Thanks everyone. That is perfect.

推荐答案

使用 closest() :

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

这篇关于获取jQuery选择器的父元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆