[英]Add class to href if it links to current page
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. 我目前正在尝试制作javascript函数,以检查页面上的链接是否链接到同一页面,如果是,则向其中添加一个类。
What I currently have: 我目前所拥有的:
$(document).ready(function() {
var currentPage = location.pathname;
if $("a[href*=currentPage]") {
$("a").addClass( "active" );
}
});
However, this doesn't seem to work. 但是,这似乎不起作用。 Any help appreciated.
任何帮助表示赞赏。
var currentPage = location.pathname;
$('a').each(function() {
var currentHref = $(this).attr('href');
if(currentHref == currentPage) {
$(this).addClass("active");
}
})
Should do the trick. 应该做到的。 Pay attention to the fact that some links might include the domain.
请注意某些链接可能包含域的事实。
You can use pure JavaScript (IE 9 and above) 您可以使用纯JavaScript(IE 9及更高版本)
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";
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.