jquery中可用addClass()和removeClass()来添加类和移除类。addClass()向被选元素添加一个或多个类,语法“$(selector).addClass(类名)”,如需添加多个类,就使用空格分隔类名。removeClass()从被选元素移除一个或多个类,语法“$(selector).removeClass(类名)”;参数可以省略,此时就会清空所有类。

本教程操作环境:windows7系统、jquery3.6.1版本、Dell G3电脑。
jquery添加类和移除类的方法
| 方法 | 描述 |
|---|---|
| addClass() | 向匹配的元素添加指定的类名。 |
| removeClass() | 从所有匹配的元素中删除全部或者指定的类。 |
jquery addClass()添加类
addClass() 方法向被选元素添加一个或多个类。
该方法不会移除已存在的 class 属性,仅仅添加一个或多个 class 属性。
提示:如需添加多个类,请使用空格分隔类名。
语法:
$(selector).addClass(class)
| 参数 | 描述 |
|---|---|
| class | 必需。规定一个或多个 class 名称。 |
示例:向第一个 p 元素添加一个类
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery-3.6.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("button").click(function() {
$("p:first").addClass("intro");
});
});
</script>
<style type="text/css">
.intro {
font-size: 120%;
color: red;
}
</style>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>向第一个 p 元素添加一个类</button>
</body>
</html>
jQuery removeClass()移除类
removeClass() 方法从被选元素移除一个或多个类。
注释:如果没有规定参数,则该方法将从被选元素中删除所有类。
语法:
$(selector).removeClass(class)
| 参数 | 描述 |
|---|---|
| class |
可选。规定要移除的 class 的名称。 如需移除若干类,请使用空格来分隔类名。 如果不设置该参数,则会移除所有类。 |
示例:移除所有 <p> 的 "intro" 类
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery-3.6.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("button").click(function() {
$("p").removeClass("intro");
});
});
</script>
<style type="text/css">
.intro {
font-size: 120%;
color: red;
}
</style>
</head>
<body>
<h1 id="h1">This is a heading</h1>
<p class="intro">This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>从第一个段落中删除类</button>
</body>
</html>
【推荐学习:jQuery视频教程、web前端视频】
以上就是jquery怎么添加类和移除类的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号