javascript - 单击元素时,JQuery 不会更改具有 `active` 类的元素

标签 javascript jquery html twitter-bootstrap

我正在使用 bootstarp 导航栏。由于单击 tav 时 bootstrap 不会自动切换 active 选项卡,因此我编写了一些 JQuery 来为我执行此操作。我以前也这样做过,但我不知道我做错了什么。

我的 HTML:

<!DOCTYPE html>
<html>
<head>
  <title>Test</title>
  <link rel="stylesheet" type="text/css" href="public\bootstrap-3.3.2-dist\css\bootstrap.min.css">
  <link rel="stylesheet" type="text/css" href="public\bootstrap-3.3.2-dist\css\bootstrap-theme.min.css">
  <link rel="stylesheet" type="text/css" href="public\styles\style.css">
  <script src="https://code.jquery.com/jquery-latest.min.js"></script>
  <script src="public\bootstrap-3.3.2-dist\js\bootstrap.min.js"></script>
  <script src="public\js\script.js"></script>
</head>
<body>
  <div class="header">
  <h1><em>This is a test</em></h1>
  </div>
  <ul class="nav nav-tabs">
    <li id="tab" class="active"><a href="1.html">Page 1</a></li>
    <li id="tab"><a href="1.html" target="content">Page 2</a></li>
    <li id="tab"><a href="1.html" target="content">Page 3</a></li>
  </ul>
</body>
</html>

我的 JQuery 代码:

$(document).ready(function() {
  $('#tab').click(function(event) {
    $('.active:first').removeClass('active');
    el = event.target;
    el.addClass('active');
  });
});

每当我单击一个选项卡时,它应该获取具有 active 类的第一个元素,删除 active 类,然后添加 active > 类到被单击的元素。但这不起作用。当我单击该选项卡时,它除了点击链接之外什么也不做。我尝试更改伪类 :first 的使用以使用 Jquery 的 .first() 但这不起作用。我以前也这样做过,但现在无法让它工作。我做错了什么?

最佳答案

您正在非 jQuery 对象上使用 .addClass() 方法。

$() 包裹 event.target --> $(event.target)

$('.tab').on('click', function (event) {
    event.preventDefault();
    $('.active').removeClass('active');
    $(event.target).closest('.tab').addClass('active');
});

一些旁注:

  • id必须是唯一的,不能重复。请改用类。
  • 由于您点击 anchor 元素,请使用 event.preventDefault() 来阻止默认行为。
  • 由于 $(event.target) 是被单击的元素,因此如果单击它,它将包含 anchor 元素。由于 active 类应该位于父 li 元素上,因此您可以使用 $(event.target).closest('.tab') 选择它 如上例所示。或者,由于事件处理程序已附加到 .tab 元素,您也可以只使用 $(this)

    $('.tab').on('click', function (event) {
        event.preventDefault();
        $('.active').removeClass('active');
        $(this).addClass('active');
    });
    

进行这些更改后,请查看 this example .

关于javascript - 单击元素时,JQuery 不会更改具有 `active` 类的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28132732/

相关文章:

html - 如何在背景中完全显示图像时使文本居中

javascript - 我们可以将 ng-bind 值存储到 php 字符串吗

javascript - document.ready 与 document.onLoad

javascript - 如何解决 JS/Jquery 动画代码流错误?

javascript - $.回调 : how to get length of the callback list

javascript - 在聚焦和模糊时更改 TinyMCE 的边框颜色

jquery mobile加载本地html页面

html - 如何在 Ruby on Rails 应用程序中更改 Index.html 的头部部分?

javascript - 客户端验证在 jQuery UI 对话框中不起作用

javascript - redux 调度 ActionCreator 上的绑定(bind)变量