jquery如何添加类和移除类

本文讲解"jquery怎么添加类和移除类",希望能够解决相关问题。

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

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>
		<h2>This is a heading</h2>
		<p>This is a paragraph.</p>
		<p>This is another paragraph.</p>
		<button>向第一个 p 元素添加一个类</button>
	</body>
</html>

jquery如何添加类和移除类

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>
		<h2 id="h2">This is a heading</h2>
		<p class="intro">This is a paragraph.</p>
		<p>This is another paragraph.</p>
		<button>从第一个段落中删除类</button>
	</body>
</html>

jquery如何添加类和移除类

关于 "jquery怎么添加类和移除类" 就介绍到此。希望多多支持编程宝库

本文讲解"jquery寻找父级的方法是什么",希望能够解决相关问题。4个方法:1、parent(),可以查找当前元素的“父元素”,语法“$(选择器).parent(表达式)”;2、parents(),可查找 ...