使用 Jquery 查找父 div 的 id

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/545978/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 09:18:56  来源:igfitidea点击:

Finding the id of a parent div using Jquery

jquerydomsemantics

提问by Rich Bradshaw

I have some html like this:

我有一些这样的html:

<div id="1">
    <p>
        Volume = <input type="text" />
        <button rel="3.93e-6" class="1" type="button">Check answer</button>
    </p>
    <div></div>
</div>

and some JS like this:

和一些像这样的JS:

$("button").click(function () {
    var buttonNo = $(this).attr('class');
    var correct = Number($(this).attr('rel'));

    validate (Number($("#"+buttonNo+" input").val()),correct);
    $("#"+buttonNo+" div").html(feedback);
});

What I'd really like is if I didn't have to have the class="1" on the button (I know numeric classes aren't valid, but this is a WIP!), so I could determine buttonNo based on the id of the parent div. In real life there are multiple sections looking like this.

我真正想要的是,如果我不必在按钮上设置 class="1"(我知道数字类无效,但这是一个 WIP!),所以我可以根据父 div 的 ID。在现实生活中,有多个部分看起来像这样。

  1. How do I find the id of the div parenting the button.

  2. What would be a more semantic way to store the answer in the button code. I want to make this as foolproof as possible for a non programmer to copy and paste without breaking things!

  1. 我如何找到作为按钮的 div 的 id。

  2. 在按钮代码中存储答案的更语义方式是什么。我想让非程序员在不破坏东西的情况下复制和粘贴尽可能万无一失!

回答by Mark

You could use event delegationon the parent div. Or use the closestmethod to find the parent of the button.

您可以在父 div 上使用事件委托。或者使用最接近的方法找到按钮的父级。

The easiest of the two is probably the closest.

两者中最简单的可能是最接近的。

var id = $("button").closest("div").prop("id");

回答by Rob Grant

1.

1.

$(this).parent().attr("id");

2.

2.

There must be a large number of ways! One could be to hide an element that contains the answer, e.g.

一定有很多方法!一种可能是隐藏包含答案的元素,例如

<div>
    Volume = <input type="text" />
    <button type="button">Check answer</button>
    <span style="display: hidden">3.93e-6&lt;/span>
    <div></div>
</div>

And then have similar jQuery code to the above to grab that:

然后使用与上面类似的 jQuery 代码来获取它:

$("button").click(function () 
{
    var correct = Number($(this).parent().children("span").text());
    validate ($(this).siblings("input").val(),correct);
    $(this).siblings("div").html(feedback);
});

bear in mind that if you put the answer in client code then they can see it :) The best way to do this is to validate it server-side, but for an app with limited scope this may not be a problem.

请记住,如果您将答案放在客户端代码中,那么他们可以看到它:) 最好的方法是在服务器端验证它,但对于范围有限的应用程序,这可能不是问题。

回答by Buu Nguyen

Try this:

尝试这个:

$("button").click(function () {
    $(this).parents("div:first").html(...);
});

回答by Ashish Sajwan

$(this).parents('div').attr('id');

回答by Pim Jager

To get the id of the parent div:

要获取父 div 的 id:

$(buttonSelector).parents('div:eq(0)').attr('id');

Also, you can refactor your code quite a bit:

此外,您可以重构代码:

$('button').click( function() {
 var correct = Number($(this).attr('rel'));
 validate(Number($(this).siblings('input').val()), correct);
 $(this).parents('div:eq(0)').html(feedback);
});

Now there is no need for a button-class

现在不需要按钮类

explanation
eq(0), means that you will select one element from the jQuery object, in this case element 0, thus the first element. http://docs.jquery.com/Selectors/eq#index
$(selector).siblings(siblingsSelector) will select all siblings (elements with the same parent) that match the siblingsSelector http://docs.jquery.com/Traversing/siblings#expr
$(selector).parents(parentsSelector) will select all parents of the elements matched by selector that match the parent selector. http://docs.jquery.com/Traversing/parents#expr
Thus: $(selector).parents('div:eq(0)'); will match the the first parent div of the elements matched by selector.

解释
eq(0),意味着您将从 jQuery 对象中选择一个元素,在本例中为元素 0,即第一个元素。http://docs.jquery.com/Selectors/eq#index
$(selector).siblings(siblingsSelector) 将选择与siblingsSelector 匹配的所有兄弟元素(具有相同父元素的元素)http://docs.jquery.com/Traversing /siblings#expr
$(selector).parents(parentsSelector) 将选择与父选择器匹配的选择器匹配的元素的所有父元素。http://docs.jquery.com/Traversing/parents#expr
因此: $(selector).parents('div:eq(0)'); 将匹配由选择器匹配的元素的第一个父 div。

You should have a look at the jQuery docs, particularly selectors and traversing:

您应该查看 jQuery 文档,尤其是选择器和遍历:

回答by Jerin K Alexander

http://jsfiddle.net/qVGwh/6/Check this

http://jsfiddle.net/qVGwh/6/检查这个

   $("#MadonwebTest").click(function () {
    var id = $("#MadonwebTest").closest("div").attr("id");
    alert(id);
    });

回答by Hamid

This can be easily done by doing:

这可以通过执行以下操作轻松完成:

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

You attach this to any object inside a table and it will return you the id of that table.

您将其附加到表内的任何对象,它将返回该表的 ID。

回答by Parrots

JQUery has a .parents() method for moving up the DOM tree you can start there.

JQUEry 有一个 .parents() 方法用于向上移动 DOM 树,您可以从那里开始。

If you're interested in doing this a more semantic way I don't think using the REL attribute on a button is the best way to semantically define "this is the answer" in your code. I'd recommend something along these lines:

如果您有兴趣以更语义化的方式执行此操作,我认为在按钮上使用 REL 属性并不是在代码中从语义上定义“这就是答案”的最佳方式。我会推荐一些类似的东西:

<p id="question1">
    <label for="input1">Volume =</label> 
    <input type="text" name="userInput1" id="userInput1" />
    <button type="button">Check answer</button>
    <input type="hidden" id="answer1" name="answer1" value="3.93e-6" />
</p>

and

$("button").click(function () {
    var correctAnswer = $(this).parent().siblings("input[type=hidden]").val();
    var userAnswer = $(this).parent().siblings("input[type=text]").val();
    validate(userAnswer, correctAnswer);
    $("#messages").html(feedback);
});

Not quite sure how your validate and feedback are working, but you get the idea.

不太确定你的验证和反馈是如何工作的,但你明白了。

回答by Cris

find() and closest() seems slightly slower than:

find() 和closest() 似乎比:

$(this).parent().attr("id");