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

时间:2011-05-17 19:46:46

标签: javascript jquery location-href

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

我试过了,但没有运气。

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

这不可能吗?

3 个答案:

答案 0 :(得分:6)

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

应该工作。

答案 1 :(得分:1)

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

(未经测试)

答案 2 :(得分:0)

您是否尝试过window.location.href而不是document.location.href?