[英]set active class to element based on child elements href attribute
I have written code for navigation. 我已经编写了导航代码。 I want to check which class is active, according to that it should set color blue for that respective tab 我想检查哪个类是活动的,根据它应该为相应的选项卡设置蓝色
My Code 我的守则
$(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>
You are placing the active on the a element, not the list Change your javascript code to this: 您将活动放在元素上,而不是列表中将您的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");
})
});
Well that is because you are adding class active to anchor element. 那是因为你正在为锚元素添加类active。 And your selector targets li elements with class active. 并且您的选择器将li元素作为活动类。 Hence you need to add class active to parent li, instead of adding it to anchor element. 因此,您需要将类active添加到parent li,而不是将其添加到anchor元素。 you can use .closest()
or .parent()
here: 你可以在这里使用.closest()
或.parent()
:
$(this).closest('li').addClass("active");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.