你如何更改 html 中的活动类

-1 html javascript jquery web

我的网站一侧有一个导航栏,但问题是当我更改导航栏中的选项卡时,活动类不会更改,这是我的代码

 <!DOCTYPE html>
<html>
<body style="background-color:yellow">

<font color="red"><div align="center"><h1>About</h1></div></font>
<head>
<style>
body {
    margin: 0;
}

ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    width: 25%;
    background-color: #875050;
    position: fixed;
    height: 100%;
    overflow: auto;
}

li a {
    display: block;
    color: #000;
    padding: 8px 16px;
    text-decoration: none;
}

li a.active {
    background-color: #4CAF50;
    color: white;
}

li a:hover:not(.active) {
    background-color: #555;
    color: white;
}
 </style>
</head>
<body>
<ul>
  <li><a class="active" href="prodject.htm">Home</a></li>
  <li><a href="prodject1.htm">News</a></li>
  <li><a href="prodject2.htm">Contact</a></li>
  <li><a href="prodject3.htm">About</a></li>
</ul>

</body>
</html>
Run Code Online (Sandbox Code Playgroud)

这是我的java脚本代码

$(".nav li").click(function() {
    if ($(".nav li").removeClass("active")) {
        $(this).removeClass("active");
    }
    $(this).addClass("active");
});
Run Code Online (Sandbox Code Playgroud)

有没有什么办法解决这一问题

Sat*_*pal 5

你没有navHTML 类

<ul class="nav">
   <li><a class="active" href="prodject.htm">Home</a></li>
</ul>
Run Code Online (Sandbox Code Playgroud)

您不需要if,直接使用带有方法的选择器。

$(".nav li").click(function() {
    $(".nav li.active").removeClass("active");
    $(this).addClass("active");
});
Run Code Online (Sandbox Code Playgroud)

或者,

$(".nav li").click(function() {
    $(this).siblings(".active").removeClass("active");
    $(this).addClass("active");
});
Run Code Online (Sandbox Code Playgroud)