我有jquery脚本,它会将clas添加到specfic li中。前三里 它添加了类但是如果点击第4个到最后的li则它不适用。请 帮助我:
html:
<ul class="sidebar-menu" id = "navigation">
<li><a href="www.site.com/dashboard">Dashboard</a></li>
<li><a href="wwww.site.com/mycoupon">My Coupons</a></li>
<li><a href="www.site.com/member">View Profile</a></li>
<li><a href="www.site.com/update">Update Profile</a></li>
</ul>
Jquery:
$(document).ready(function() {
var current_page = document.URL;
if (current_page.match(/dashboard/)){
$("ul#navigation li:eq(0)").addClass('selected sel');
}
else if (current_page.match(/mycoupon/)){
$("ul#navigation li:eq(1)").addClass('selected sel');
}
else if (current_page.match(/member/)){
$("ul#navigation li:eq(2)").addClass('selected sel');
}
else if (current_page.match(/update/)){
$("ul#navigation li:eq(3)").addClass('selected sel');
}
else { // don't mark any nav links as selected
$("ul#navigation li").removeClass('selected sel');
}
});
答案 0 :(得分:1)
您可以像这样使用
,而不是为每个菜单编写代码$(document).ready(function() {
var current_page = document.URL;
$("#navigation li a").filter(function() {
return current_page.indexOf($(this).attr("href")) > -1
}).closest("li").addClass("selected sel");
});