当单击<li>标签下的<a>标签时,我想将活动类添加到该<li>标签中

I want to add class active to <li> tag when <a> tag under that <li> tag is clicked

本文关键字:标签 li 添加 活动 单击      更新时间:2023-09-26

My index.html具有以下DOM结构:

ul -> class:nav nav-tabs -> li -> a  

我想在单击该<li>中的<a>元素时将类.active添加到<li>元素。我已经编写了这段代码,但它不起作用:

主.js

var main = function(){
    $("a").click(function() {
        $('li').removeClass('.active');
        $(this).addClass(".active"); 
    });
};
$(document).ready(main);

试试这个:

var main = function(){
   $("a").click(function() {
      //travel up the DOM tree to the "closest" li element, add "active" class to it
      $(this).closest('li').addClass("active"); 
   });
};
$(document).ready(main);

所以你很接近,但你有几个问题:

  1. 您希望将新的 active 类应用于包含li ,而不是到正在点击的a
  2. addClass()removeClass() 不需要以 . 为前缀。

.name 是用于查找具有 name 类的元素的选择addClassremoveClass期望类名,而不是选择器。要添加"active"类,只需给它字符串"active"

$(this).addClass('active')

您还将类直接添加到单击的链接中。如果要将其添加到包含<li>,请使用:

$(this).parent().addClass('active')

您尝试操作li,但您操作的是a标签。

您需要使用:

$(this).closest('li').addClass("active");

编辑

并且也不使用其他人提到的.字符

你需要提到类名而不.

$(this).addClass("active");