jQuery:活动状态:将 AddClass 添加到包含 document.href 作为 href 的链接

jQuery: Active state: AddClass to a link that contains the document.href as href

本文关键字:href 作为 document 链接 包含 活动状态 AddClass 添加 jQuery      更新时间:2023-09-26

我想知道是否可以将Class添加到与document.href具有相同href的链接中?

我试过了,但没有任何运气。

if ($("a").attr("href") == document.location.href) {
    $(this).addClass("active");
}

这不可能吗??

$("a").filter(function() {
    return this.href === document.location.href;
}).addClass("active");

应该工作。

$("a[href=" + document.location.href + "]").addClass("active");

(未测试)

你有没有尝试过window.location.href而不是document.location.href?