如何瞄准类的子类(特别是添加和删除该类)


<div class="nav">
  <ul class="active">
    <li><a class="current" href=index.html>About</a></li>
    <li><a href=portfolio.html>Portfolio</a></li>
    <li><a href=essay.html>Essays</a></li>
    <li><a href=resources.html>Resources</a></li>
    <li><a href=research.html>Research</a></li>
    <li id="last"><a href=contact.html>Contact</a></li>
  </ul>
</div>

我已经使用CSS使li标签成为一个水平列表,并在鼠标悬停时改变颜色。

然而,我试图使导航栏呈现当前的活动链接,这意味着如果我目前在index.html上,我希望使用类"current"突出显示"ABOUT"li

当页面为当前页面时,类current将应用于li。经过一番研究,这是我找到的最接近的东西,但它不起作用。

$document.ready(function(){
    $('.active li').on('click',function(){
        $(this).addClass('.nav .current').sublings().removeClass('active')
    });

下面是我为菜单导航设置的CSS。

.nav li {
  display:inline;
  margin-right:25px;
  font-size:13px;
  padding-top:6px;
  font-weight:bold;
}
.active li a {
  display: inline-block;
  border-top-style:solid;
  border-top-color:#8D919E; 
  border-top-width: 6px;
  padding-top: 6px;
}

.nav .current {
  color:#30B7E7;
  border-top-color:#30B7E7;
}

我想以某种方式瞄准。nav .current类并将其添加到li并从最后的li中删除它。

编辑:我想出了一个超级愚蠢的方法,通过html来做到这一点。我将类current应用于索引页的第一个LI in,其余的没有这个类。然后对于第二页,我将class current应用于该LI,并将其从第一页中删除。这是一个愚蠢的修复,但我不能得到任何JS代码工作的原因。

你也可以这样做:

$('.active li a').on('click', function(e) {
    //prevent the default behaviour of the link 
    //that would have navigated to the next page
    e.preventDefault();
    var currentListEl = $(this).parent("li");//get the a tags parent li
    currentListEl.siblings().removeClass('current');//remove 'current' from its siblings
    currentListEl.addClass('current');//add 'current' to the li
    //navigate to the "current" page or load it with ajax
});

jquery是错误的。我觉得你有点迷路了。应该是:

$('.active li').on('click',function() {
    $('.current').removeClass('current');      //<--- Not efficient, but will work
    $(this).children('a').addClass('current'); //<--- You want to add current to a tag?
});

我看到的三个错误是

  • $document.ready(function(){有关闭的}) ?在你的例子中没有。
  • subsulings是打字错误
  • addClass('.nav .current')使用错误。你的目标不是CSS选择器而是添加一个类

要添加一个与页面URL匹配的类,您可以这样做-

var url = window.location.pathname;
var currentPage = url.substring(url.lastIndexOf('/')+1);
$('a[href="' + currentPage + '"]').closest('li').addClass('current active'); // adds highlight to current page element
$('li a').on('click', function(e) {
    e.preventDefault();
    var thisHREF = $(this).attr('href');
    $(this).parent().siblings().removeClass('active');
    $('a[href="' + thisHREF + '"]').closest('li').addClass('active');
});

最新更新