如何解决如果未检测到路径名,则在<link>中添加class
| 当window.location.pathname为NULL时,我们想在链接的第一个孩子上添加一个类 的HTML代码是 <nav>
<a href=\"index.php\">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>
网址是www.nicadpower.com/
window.location.pathname.substring(1);
除了NULL之外不会产生任何其他结果。
检测到NULL后,我们希望$(\'nav a \')第一个孩子添加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>
解决方法
如果
window.location.pathname.substring(1);
给您null
,请使用此代码:
if (window.location.pathname.substring(1) == null){
$(\'nav a:first-child\').addClass(\'current\');
}
但是...我不认为它会给你空值,可能不会给你4英镑,所以这样做更好:
if (window.location.pathname.substring(1).length==0){
$(\'nav a:first-child\').addClass(\'current\');
}
, pathname
永远不是null
,它总是至少包含/
-请参阅W3C规范。
因此,您只需要检查字符串的长度不超过一个即可:
if (window.location.pathname.length <= 1) {
$(\'nav a:first-child\').addClass(\'current\');
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。