我有这个ul树列表。
<ul class="sidebar-menu" id="nav-accordion">
<li class="sub-menu">
<a href="file0.asp">
<i class="fa fa-dashboard"></i>
<span>Dashboard</span>
</a>
<ul class="sub">
<li><a href="file.html">Pricefile</a></li>
<li><a href="file2.html">Pricefile</a></li>
<li><a href="file3.html">Pricefile</a></li>
</ul>
</li>
</ul>我有这个脚本来定位当前页面,并设置将当前li类添加到.active。到目前一切尚好。
但我也需要在我的..。对.active进行分类。使用父函数,我如何做到这一点?
var str=location.href.toLowerCase();
$("#sidebar li a").each(function() {
if (str.indexOf(this.href.toLowerCase()) > -1) {
$(this).parent().addClass("active");
$(this).parent().parent().parent('a').addClass("active"); // THIS LINE
}
});发布于 2015-01-18 20:48:43
你这样做是对的,只要parent()上的多姆树。
但是,与使用parent().parent().parent().parent()等不同,我建议使用closest() (文档)来搜索dom树中的匹配元素。例如
$('li.active').closest('ul').addClass('active');编辑:
如果您试图在元素中获取某些内容,可以使用find()。可能是这样的:
$('li.active').find('a').addClass('active');编辑:
啊,对不起,所以你会去:
$('li.active').closest('li').find('a:first-child').addClass('active');或
$(this).closest('.sub-menu').find('a:first-child').addClass('active');https://stackoverflow.com/questions/28014634
复制相似问题