下面是我的代码,我想将“活动类”添加到活动链接的li元素。意味着我想将活动类添加到当前活动链接的li标签。这是我已经完成但不能正常工作。提前谢谢你。
$('#rightnav').ready(function() {
var page = window.location.href.split("/")[5];
if (page == "") { page = "dashboard.php"; }
$(this).find("ul#rightnav>li a[href$="+page+"]").addClass("active");
});
<ul class="nav navbar-nav side-nav" id="rightnav">
<li><a href="dashboard.php"><i class="fa fa-dashboard"></i> Dashboard</a></li>
<li><a href="products_list.php"><i class="fa fa-bar-chart-o"></i> Products</a></li>
<li><a href="charts.html"><i class="fa fa-bar-chart-o"></i> Charts</a></li>
<li><a href="tables.html"><i class="fa fa-table"></i> Tables</a></li>
<li><a href="forms.html"><i class="fa fa-edit"></i> Forms</a></li>
<li><a href="typography.html"><i class="fa fa-font"></i> Typography</a></li>
<li><a href="bootstrap-elements.html"><i class="fa fa-desktop"></i> Bootstrap Elements</a></li>
<li><a href="bootstrap-grid.html"><i class="fa fa-wrench"></i> Bootstrap Grid</a></li>
<li><a href="blank-page.html"><i class="fa fa-file"></i> Blank Page</a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown"><i class="fa fa-caret-square-o-down"></i> Dropdown <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="#">Dropdown Item</a></li>
<li><a href="#">Another Item</a></li>
<li><a href="#">Third Item</a></li>
<li><a href="#">Last Item</a></li>
</ul>
</li>
</ul>
答案 0 :(得分:0)
尝试
$(document).ready(function () {
var page = window.location.href.split("/")[5];
if (page == "") {
page = "dashboard.php";
}
$('#rightnav > li').has('a[href$="' + page + '"]').addClass("active");
});
演示:Fiddle
答案 1 :(得分:0)
$(this).find("ul#rightnav>li a[href$="+page+"]").parent().addClass("active");
它的作用是获取与查询字符串parent
匹配的所有元素,并.addClass("active")
。