jQuery 通过按类搜索来获取元素的 id
这是我的 html :
<div id="my_box_one" class="head-div">
<div>
<div class="some_box">a</div>
<div class="some_box">b</div>
</div>
</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
});
});
我可以执行以下操作,它会正常工作,但它不会'看来是对的。
var abc = $(this).parent("div").parent("div").attr("id");
This is my 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")
$(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");
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 .closest( 选择器 ),例如:
http://api.jquery.com/closest/
.parent( 选择器 ) 仅选择元素的直接父元素。
You can use .closest( selector ), for example:
http://api.jquery.com/closest/
.parent( selector ) selects only immediate parent of the element.
parentsUntil
获取所有父元素,直到选择器匹配为止。它不包括匹配的元素。您正在尝试获取中间div
的id
,这显然是未定义的。您需要使用
closest
,它会沿着 DOM 树向上查找,直到找到与选择器匹配的元素,然后仅返回该元素:编辑:为了提高速度,但在更改标记时灵活性较差,可以使用
parentNode
属性: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 theid
of the interveningdiv
, which is obviously undefined.You need to use
closest
, which goes up the DOM tree until it finds an element matching the selector, then returns only that element:Edit: for extra speed, but less flexibility in the event that you change your markup, you could use the
parentNode
property: