【问题标题】:Getting a parent element for a jquery selector获取 jquery 选择器的父元素
【发布时间】:2011-12-07 15:10:56
【问题描述】:

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

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

用户可以连续单击单元格中的特定元素。我想找到被点击的行。

例如:

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

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

有没有办法通过多次使用 .parent() 来获取包含该元素的行?

更新:谢谢大家。这是完美的。

【问题讨论】:

标签: jquery parent


【解决方案1】:

使用closest():

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

【讨论】:

    【解决方案2】:

    使用closest:

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

    来自文档:

    获取第一个匹配选择器的元素,从 当前元素并在 DOM 树中向上移动。

    【讨论】:

      【解决方案3】:

      你可以用这个。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-24
        • 2012-12-23
        • 2017-06-17
        • 1970-01-01
        相关资源
        最近更新 更多