jQuery 通过按类搜索元素来获取元素的 id
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5841650/
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
jQuery get id of element by searching for it by class
提问by DMin
This is my html :
这是我的 html:
<div id="my_box_one" class="head-div">
<div>
<div class="some_box">a</div>
<div class="some_box">b</div>
</div>
</div>
I want to get the ID of the parent div("#my_box_one") using the class of that div(".head-div")
我想使用该 div(".head-div") 的类获取父 div("#my_box_one") 的 ID
$(document).ready(function(){
$(".some_box").click(function(){
var abc = $(this).parentsUntil(".head-div").attr("id");
// also tried $(this).parent(".head-div") -- same effect
alert(abc); // Shows as Undefined
});
});
I can do the following and it will work okay, but it doesn't seem right.
我可以执行以下操作,它会正常工作,但似乎不对。
var abc = $(this).parent("div").parent("div").attr("id");
回答by Lapple
You can use .closest( selector ), for example:
您可以使用.closest( selector ),例如:
var abc = $(this).closest(".head-div").attr("id");
http://api.jquery.com/closest/
http://api.jquery.com/closest/
.parent( selector )selects only immediate parent of the element.
.parent( selector )只选择元素的直接父元素。
回答by lonesomeday
parentsUntil
gets all the parent elements until the one matched by the selector. It does not include the element matched. You're trying to get the id
of the intervening div
, which is obviously undefined.
parentsUntil
获取所有父元素,直到与选择器匹配的元素为止。它不包括匹配的元素。您正在尝试获取id
中间人的div
,这显然是未定义的。
You need to use closest
, which goes up the DOM tree until it finds an element matching the selector, then returns onlythat element:
您需要使用closest
,它会沿着 DOM 树向上移动,直到找到与选择器匹配的元素,然后仅返回该元素:
var abc = $(this).closest(".head-div").attr("id");
Edit: for extra speed, but less flexibility in the event that you change your markup, you could use the parentNode
property:
编辑:为了获得额外的速度,但在更改标记的情况下灵活性较低,您可以使用该parentNode
属性:
var abc = this.parentNode.parentNode.id;