如果单击某行的子元素,如何获取该行的 id 属性?

发布于 2024-10-09 07:58:40 字数 569 浏览 0 评论 0原文

如何返回链接所在行的 id 属性?我尝试过不同的变体,但我能得到的最好的是“未定义”...

html 看起来像这样:

<tr id="30">
  <td>Parker</td>
  <td><a href="#" id="id783900" class="section-id">Select</a></td>
</tr>

我尝试过的事情之一是这样的:

$("a.section-id").click(function() {
  var parenttr = $(this).parent().parent().attr("id");
  alert(parenttr);
});

我也尝试过这个:

$("a.section-id").click(function() {
  var parenttr = $(this).parent('tr').attr("id");
  alert(parenttr);
});

How do I return the id attribute of the row in which a link resides? I've tried different variations, but the best I've been able to get is "undefined"...

The html looks like this:

<tr id="30">
  <td>Parker</td>
  <td><a href="#" id="id783900" class="section-id">Select</a></td>
</tr>

One of the things I tried is this:

$("a.section-id").click(function() {
  var parenttr = $(this).parent().parent().attr("id");
  alert(parenttr);
});

I also tried this:

$("a.section-id").click(function() {
  var parenttr = $(this).parent('tr').attr("id");
  alert(parenttr);
});

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

徒留西风 2024-10-16 07:58:40

尝试:

$(this).closest('tr').attr('id');

Try:

$(this).closest('tr').attr('id');
十六岁半 2024-10-16 07:58:40

Parent() 仅检查直接父级。要遍历树,请使用parents()。

var parenttr = $(this).parents('tr').attr("id");

编辑:

树面是正确的。对于此用例,请使用closest()。 parents() 做了一些你不需要的额外工作来解决这个问题。

parent() only checks the immediate parent. To traverse up the tree, use parents().

var parenttr = $(this).parents('tr').attr("id");

EDIT:

treeface is correct. Use closest() for this use case. parents() does extra work that you don't need for this problem.

月棠 2024-10-16 07:58:40
$('a.section-id').click(function(e) {
    var parent_id = $(this).parents('tr:first').attr('id');
    alert(parent_id);
    e.preventDefault();
});
$('a.section-id').click(function(e) {
    var parent_id = $(this).parents('tr:first').attr('id');
    alert(parent_id);
    e.preventDefault();
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文