[英]jquery traversing to find a parent's parent
HTML: HTML:
<li class="comment">
<div class="p_comm">
<div class="avatar"><img src="/img/1.jpg"></div>
<div class="c_auth">author<a class="del" title="delete it!" rel="19">x</a></div>
<div class="c_cont w">what ever</div>
<div class="c_time">12-23 13:22:15</div>
</div>
</li>
I want to find the parent li relative to the <a>
in this section. 我想找到相对于本节中
<a>
的父li。 I can't find a function to do this. 我找不到这样做的功能。 I've tried
prev(),parentsUntil()
none of them can do this. 我试过
prev(),parentsUntil()
没有人能做到这一点。 Currently i have to use $(this).parent().parent().parent()
to reach <li>
. 目前我必须使用
$(this).parent().parent().parent()
来达到<li>
。 Is there a function to find parent <li>
directly? 是否有直接查找父
<li>
的功能?
或这个:
$(this).parents('li');
var p = $('.del').parents('li');
console.log(p);
http://jsfiddle.net/hZY8R/ http://jsfiddle.net/hZY8R/
The .parents() and .parent() methods are similar, except that the latter only travels a single level up the DOM tree.
.parents()和.parent()方法类似,只是后者只在DOM树上运行一个级别。
As you can see, when you use parents with a selector, you will be fine. 正如您所看到的,当您使用带选择器的父母时,您会没事的。
You should use closest()
which will traverse up the DOM until it finds the element you're after: 你应该使用
closest()
来遍历DOM,直到它找到你所追求的元素:
$('a').closest('li');
If you were doing this the other way around (ie you had the li
and wanted to find the a
) you would use: 如果你反过来这样做(即你有
li
并想找到a
),你会使用:
$('li').find('a');
.parent()
by itself just refers to the immediate ancestor of a node, but you can also do: .parent()
本身只是指节点的直接祖先,但你也可以这样做:
var li = $('a.del').parents('li.comment');
to have JQuery go back up the DOM tree until it finds a matching ancestor node. 让JQuery返回DOM树,直到找到匹配的祖先节点。 In this case,
li
will point at the a
's li
ancestor. 在这种情况下,
li
将指向a
的li
祖先。
edit: forgot that .parent()
only goes up one level, while .parents()
goes up the entire tree. 编辑:忘了
.parent()
只上升一级,而.parents()
上升到整个树。 Both accept a selector argument, however. 但是,两者都接受选择器参数。
$("a.del").click(function() {
alert($(this).closest("li").attr("class"))
})
Use the following code: 使用以下代码:
$(function(){
$("a").click(function(){
$(this).parents("li").hide();
})
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.