[英]jQuery: Select all parents of the selected LI element
I have a hierarchical UL list. 我有一个分层的UL列表。 How to - using jQuery - get the all parents of the selected LI element and change the
<a>
's background color inside each parent ? 如何使用jQuery获取所选LI元素的所有父级,并更改每个父级内部
<a>
的背景颜色?
<ul id="nav">
<li>
<a href="#">A</a>
<ul>
<li>
<a href="#">B</a>
<ul>
<li><a href="#">B1</a></li>
<li><a href="#">B2</a></li>
<li><a href="#">B3</a></li>
<li><a href="#">B4</a></li>
<li><a href="#">B5</a></li>
</ul>
</li>
<li>
<a href="#">C</a>
<ul>
<li><a href="#">C1</a></li>
<li><a href="#">C2</a></li>
<li><a href="#">C3</a></li>
</ul>
</li>
</ul>
If I eg select <a href="#">B4</a>
, <a href="#">B</a>
and <a href="#">A</a>
will be also selected 如果我选择
<a href="#">B4</a>
,还将选择<a href="#">B</a>
和<a href="#">A</a>
The following will bind a click
event to all <li>
elements, and literally apply a background color to all parents and itself. 以下内容将
click
事件绑定到所有<li>
元素,并从字面上将背景色应用于所有父项及其本身。
$('li').click(function() {
$(this).parents().andSelf().css('background-color', 'red');
});
jQuery docs: jQuery文档:
假设A和B都是UL
元素,则以下代码应该起作用:
$(this).parents('ul').addClass('new_class');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.