[英]Add class to href if it links to current page
我目前正在嘗試制作javascript函數,以檢查頁面上的鏈接是否鏈接到同一頁面,如果是,則向其中添加一個類。
我目前所擁有的:
$(document).ready(function() {
var currentPage = location.pathname;
if $("a[href*=currentPage]") {
$("a").addClass( "active" );
}
});
但是,這似乎不起作用。 任何幫助表示贊賞。
var currentPage = location.pathname;
$('a').each(function() {
var currentHref = $(this).attr('href');
if(currentHref == currentPage) {
$(this).addClass("active");
}
})
應該做到的。 請注意某些鏈接可能包含域的事實。
您可以使用純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.