Adding class in a <link> if no pathname is detected
We want to add a class on our the first-child of the link when window.location.pathname is NULL
the html code is
<nav>
<a href="index.php">Home</a>
<a href="company.php"&开发者_开发知识库gt;Company</a>
<a href="products.php">Products</a>
<a href="technical.php">Technical</a>
<a href="services.php">Services</a>
<a href="contactus.php">Contact Us</a>
</nav>
and the URL is www.nicadpower.com/ doing
window.location.pathname.substring(1);
Would not result anything except a NULL.
After detecting a NULL we want the $('nav a') first-child to add the class="current"
<nav>
<a href="index.php" class="current">Home</a>
<a href="company.php">Company</a>
<a href="products.php">Products</a>
<a href="technical.php">Technical</a>
<a href="services.php">Services</a>
<a href="contactus.php">Contact Us</a>
</nav>
If window.location.pathname.substring(1);
gives you null
then just use this:
if (window.location.pathname.substring(1) == null){
$('nav a:first-child').addClass('current');
}
but... I don't think it'll give you null, prolly it won't give you null
, so you are better off doing this:
if (window.location.pathname.substring(1).length==0){
$('nav a:first-child').addClass('current');
}
pathname
is never null
, it always contains at least /
-see the W3C spec.
So, you just need to check that the length of the string isn't more than one:
if (window.location.pathname.length <= 1) {
$('nav a:first-child').addClass('current');
}
精彩评论