javascript - 如何在 li 的 twitter bootstrap 中切换事件类?

标签 javascript html twitter-bootstrap

我有以下将在页面之间切换的标题:

<nav class="navbar navbar-inverse navbar-fixed-top">
  <div class="container">
    <div class="navbar-collapse collapse">
      <form method="post">
        <ul class="nav navbar-nav">
          <li class="active"><a href="active.php">Active Tags</a></li>
          <li><a href="archived.php">Archived Tags</a></li>
        </ul>
      </form>
    </div>
  </div>
</nav>

和以下 jQuery 在点击时切换事件 li:

$('.navbar li').click(function(e) {
  $('.navbar li.active').removeClass('active');
  var $this = $(this);
  if (!$this.hasClass('active')) {
    $this.addClass('active');
  }
  e.preventDefault();
});

仅当 e.preventDefault(); 被注释掉时才能在页面之间移动,但如果没有此行,事件类切换将无法工作...我是否必须更改我的 href's 某种类型的 onclick jQuery 函数 或隐藏表单的 php $_POST 以在页面之间移动,同时保留 active li's 之间的切换?我是 javascript/html/php 的新手,因此非常鼓励和鼓励尽可能多的细节和推理。

最佳答案

是的,你是对的,e.preventDefault() 只会切换 li 上的事件类并限制 anchor 执行其操作。

同时,将其更改为 e.stopPropagation() 将允许两个操作自行执行,而无需将其事件通知给父处理程序。

Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

因此,您可以将其更改为:

$('.navbar li').click(function(e) {
    e.stopPropagation();

    $('.navbar li.active').removeClass('active');
    var $this = $(this);

    if (!$this.hasClass('active')) {
        $this.addClass('active');
    }
});

DEMO

关于javascript - 如何在 li 的 twitter bootstrap 中切换事件类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34282091/

相关文章:

html - Bootstrap 导航栏中的居中链接(在 li 内)

jquery - 滚动时如何更改导航栏内容?

html - Bootstrap 导航栏下拉菜单悬停颜色折叠不起作用

javascript - 如何过滤掉除了与 JavaScript 中特定模式匹配的字符之外的非数字字符?

javascript - 如何替换字符串 url

javascript - 根据所选文本转到 URL 的书签

html - 如何仅在选中时提交复选框,仅在未选中时以及在选中或未选中时都提交

javascript - 制作我自己的 ForEach() javascript - 元素未定义

javascript - NLS : custom languages handler in single html view

html - 从 psd 文件创建主题的一些 CSS 问题