当导航位于外部文件中时,如何使用 jQuery 将 class 添加到导航 ul li a 中?

How to add a class to a nav ul li a using jQuery when the nav is in an external file?

我有一个仪表板,左侧有导航。导航在名为 nav.html.

的外部文件中声明

在每个页面中,我使用 jQuery 加载导航:

  <script>
     $(function () {
        $.get("nav.html", function (data) {
        $("nav").append(data);
        });
     });
  </script>

现在我尝试在活动的 a 元素上添加一个 class 但我没有找到方法...

非常感谢您的帮助。

您没有显示 nav.html 的结构,但我假设您知道应该激活哪个元素。一种可能的方法:

$.get("nav.html", function(navHtml) {
  var $navHtml = $(navHtml);
  var $activeLink = $navHtml.find('a[href="' + getActiveLink() + '"]'); // for example
  $activeLink.addClass('active');
  $("nav").append($navHtml);
});

重点是创建一个 jQuery 对象来包装尚未附加到 window.document 的 HTML 元素 - 此元素是通过解析 html 文件创建的。您可以像处理 DOM 中的 'real ones' 一样处理此对象 - 特别是,使用 .find() 方法查找特定元素,然后将特定的 class 添加到该元素.addClass().

附加后,您应该能够修改元素。顺便说一句,您可以使用 .load() 来组合 $.get.html()。在其回调函数中,this 将是您将 HTML 加载到的 nav 元素,因此您可以使用它来找到 DOM 元素。

$("nav").load("nav.html", function() {
    $(this).find("a").addClass("active");
});