jquery - 在显示相应 <div> 的 <button> 上添加 .active 类

标签 jquery html css

我正在开发一个在单个页面内打开/隐藏 div 的菜单。

我想做的是在当前单击的菜单项上应用一个类(.active),只要连接到它的 div 打开。一旦 div 关闭,或选择其他菜单项,类就会消失/应用于其他菜单项。

我尝试选择 $(".your_selector li").addClass("active");但它什么也不做,只是将所有菜单项标记为事件状态,如您所料。

你会如何解决这个问题?这是 fiddle http://jsfiddle.net/4DGUV/3/

提前致谢

最佳答案

更改为此脚本:http://jsfiddle.net/4DGUV/7/

$('document').ready(function () {
  $('button').click(function () {      //<----click the buttons
      $('button').removeClass('active'); //<-----remove the class from the button
      $(this).addClass('active'); //<---add the class to currently clicked button
      var $div = $('#' + $(this).data('href'));
      $('.demo').not($div).hide();
      $div.slideToggle();
   });
});

或者更好的方法:http://jsfiddle.net/4DGUV/8/

$('document').ready(function () {
  $('.menu li').click(function () {
    $(this).siblings().removeClass('active');
    $(this).addClass('active');
    var $div = $('#' + $(this).data('href'));
    $('.demo').not($div).hide();
    $div.slideToggle();
  });
});

那么你的html应该是这样的:

<div class="menu">
  <ul>
    <li> <a href='#' id="show2" data-href="vission1">news</a>

    </li>
    <li> <a href='#' id="show3" data-href="mteam">team</a>

    </li>
    <li> <a href='#' id="show1" data-href="mission1">download</a>

    </li>
  </ul>
</div>

关于jquery - 在显示相应 <div> 的 <button> 上添加 .active 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14830228/

相关文章:

jQuery 在 asp net core 2 razor 中设置日期值

jQuery TypeWatch - 扩展空输入?

javascript - 什么是 strophe 以及如何将它与 JQuery 一起使用?

javascript - 使用 nth-child if 语句更改 JQuery .append 输出

html - 无法在 html 中显示图像。授予的所有权限和正确的路径

CSS 菜单项未在 Chrome 中显示

html - 我的 CSS slider 不起作用

css - npm install --save bootstrap 之后我找不到 bootstrap.min.css

html - 如何引用 HTML 页面的特定位置?

javascript - 如何制作圆 Angular 和弧形的connect4板?