[英]How to apply an active css class to li based on its child <a> href
[英]set active class to element based on child elements href attribute
我已經編寫了導航代碼。 我想檢查哪個類是活動的,根據它應該為相應的選項卡設置藍色
我的守則
$(function() { var pgurl = window.location.href.substr(window.location.href.lastIndexOf("/") + 1); $("#tslcNav ul li a").each(function() { if ($(this).attr("href") == pgurl || $(this).attr("href") == '') $(this).addClass("active"); }) });
.tslcNav li:hover, .tslcNav li.active, .tslcNav li.active { background: none; border-color: #009FD6; color: #009FD6; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script> <div class="tslcNav" role="navigation"> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li><a href="index.html">Home</a></li> <li><a href="manage.html">Manage </a></li> <li><a href="welcome.html">welcome/a></li> <li><a href="security.html">Security </a></li> </ul> </div> <!--/.nav-collapse --> </div>
您將活動放在元素上,而不是列表中將您的javascript代碼更改為:
$(function() {
var pgurl = window.location.href.substr(window.location.href.lastIndexOf("/")+1);
$(".tslcNav ul li a").each(function(){
if($(this).attr("href") == pgurl || $(this).attr("href") == '' )
$(this).parent().addClass("active");
})
});
那是因為你正在為錨元素添加類active。 並且您的選擇器將li元素作為活動類。 因此,您需要將類active添加到parent li,而不是將其添加到anchor元素。 你可以在這里使用.closest()
或.parent()
:
$(this).closest('li').addClass("active");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.