[英]jquery closest returns undefined if apply on class attribute
While running following jquery code i am constantly getting 'undefined' in alert box. 在运行以下jQuery代码时,我不断在警报框中得到“未定义”。 If i replace class="back" with id="back" and reflect same in jquery code , it works fine. 如果我将id =“ back”替换为class =“ back”并在jquery代码中反映出来,则效果很好。 But i am in situation such that closest need to be of class not an id. 但是我处于这样的情况,最接近的需要是类而不是id。 How to resolve this? 如何解决呢?
HTML : HTML:
<div id="up">
<div id="boom">
<div class="back"> </div>
</div>
</div>
JQUERY : JQUERY:
$(document).ready(function(){
alert($(".back").closest("div").attr("id"));
});
.closest
starts from the current node. .closest
从当前节点开始。 But this node haven't got id
attribute. 但是该节点没有id
属性。 You need to change the selector in in .closest
as this: 您需要在.closest
更改选择器,如下所示:
$(document).ready(function(){
alert($('.back').closest('div[id]').attr('id'));
});
Now you are searching for a div
which has id
as an attribute. 现在,您正在搜索以id
为属性的div
。
that is because your 那是因为你
<div class="back">
doesn't have id attribute so it will be undefined, check with 没有id属性,因此它将是不确定的,请检查
.attr("class")
it will return class name 它将返回类名
You can also use this 你也可以用这个
$(document).ready(function(){
alert($(".back").parents("div").attr("id"));
});
closest()
method checks from the current node, so if you want to find the first anchester(parent) div tag of the class = "back"
then it should not be the div tag so you need to change the div tag to span or other tags closest()
方法从当前节点进行检查,因此,如果要查找class = "back"
的第一个anchester(父)div标签,则它不应是div标签,因此您需要将div标签更改为span或其他标签
$(document).ready(function() { console.log($(".back").closest("div").attr('id')); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> <div id="up"> <div id="boom"> <span class="back"> </span> </div> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.