如果链接到当前页面,则将类添加到href [英] Add class to href if it links to current page
本文介绍了如果链接到当前页面,则将类添加到href的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我当前正在尝试使用javascript函数来检查页面上的链接是否链接到同一页面,如果是,则向其中添加一个类.
I'm currently trying to make a javascript function to check if a link on the page links to the same page, and if so, add a class to it.
我目前拥有的东西:
$(document).ready(function() {
var currentPage = location.pathname;
if $("a[href*=currentPage]") {
$("a").addClass( "active" );
}
});
但是,这似乎不起作用. 任何帮助表示赞赏.
However, this doesn't seem to work. Any help appreciated.
推荐答案
您可以使用纯JavaScript(IE 9及更高版本)
You can use pure JavaScript (IE 9 and above)
var currentPage = location.href;
var allA = document.getElementsByTagName('A');
for(var i = 0, len = allA.length; i < len; i++) {
if(allA[i].href == currentPage) {
allA[i].className = "active";
}
}
这篇关于如果链接到当前页面,则将类添加到href的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文