jquery - 如何定位一个类的子类(特别是添加和删除这个类)

标签 jquery html css

<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 就会应用于 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 执行此操作的 super 愚蠢的方法。我在索引页的第一个 LI 中应用了 current 类,其余的都没有这个类。然后对于第二页,我将 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 - 如何定位一个类的子类(特别是添加和删除这个类),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23687252/

相关文章:

javascript - PHP 表中每一行的删除按钮

jquery - 用 jquery 改变复杂的背景

html - 给 float 的 div 添加边距

asp.net - 更改 Asp 的样式/外观 :CheckBox using CSS

javascript - 尝试将过渡效果应用于悬停

javascript - Jquery用换行符附加文本数据

javascript - WebKit 中带有滚轮的生涩视差

javascript - 图片上传前预览时通过id获取图片

html - 为什么 flex 元素不缩小过去的内容大小?

html - 我怎样才能让我的网站在 1920 x 1080 和 3840 × 2160 上看起来完全一样