添加类,最近的div

时间:2016-07-28 07:20:57

标签: jquery html css

这几乎花了3个小时。什么都没找到。

这是我的代码.. 3个单独的URL文件。 (更新)

<div id="menu">
<a href="blue.php">
<div class="list">
Content_here
</div>
</a>

<a href="yallow.php">
<div class="list">
Content_here
</div>
</a>

<a href="black.php">
<div class="list">
Content_here
</div>
</a>
</div>

在当前网址上添加课程

<div id="menu">
<a href="#">
<div class="list active">
content_here
</div>
</a>
</div>

这是:

$("#menu a").each(function(index) {
    if($.trim(this.href) == window.location) {
        $(this).closest('div').addClass("active");
    }
});

当前active上没有class URL。 ...

2 个答案:

答案 0 :(得分:1)

closest() 方法用于获取祖先元素。因为div位于a内,使用 children() find() 方法。

$(this).find('div').addClass("active");

select it based on the this context

$('div', this).addClass("active");

虽然要获取当前页面网址,请使用window.location.href

$("#menu a").each(function(index) {
    if($.trim(this.href) == window.location.href) {
        $('div', this).addClass("active");
    }
});

或将条件用作window.location.pathname == $(this).attr('href')

答案 1 :(得分:0)

试试这个:

$("[url="+window.location.origin+"]").addClass("active")

请注意window.location是一个对象而不是字符串

相关问题