jquery怎么增加类

青灯夜游
青灯夜游原创
2022-05-18 19:50:181868浏览

两种方法:1、用attr(),只需给class属性添加值,语法“元素对象.attr("class","类名");”。2、用addClass(),给添加一个或多个类,语法“元素对象.addClass("类名")”,若增多个类,用空格分隔类名。

本教程操作环境:windows7系统、jquery1.10.2版本、Dell G3电脑。

jquery增加类的两种方法

1、使用attr()

attr()可以设置被选元素的属性值,当属性为“class”时增加类。

该种方法用于之前没有类时,新增类。

示例:向第一个 p 元素添加一个类

<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<script src="js/jquery-1.10.2.min.js"></script>
		<script type="text/javascript">
			$(document).ready(function() {
				$("button").click(function() {
					$("p:first").attr("class","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>

2.gif

2、使用addClass()

addClass() 方法向被选元素添加一个或多个类。

该方法不会移除已存在的 class 属性,仅仅添加一个或多个 class 属性。如需添加多个类,请使用空格分隔类名。

示例:向第二个 p 元素添加一个类

<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<script src="js/jquery-1.10.2.min.js"></script>
		<script type="text/javascript">
			$(document).ready(function() {
				$("button").click(function() {
					$("p:nth-child(3)").addClass("intro");
				});
			});
		</script>
		<style type="text/css">
			.intro {
				font-size: 120%;
				color: red;
			}
		</style>
	</head>

	<body>
		<h1>一个大标题</h1>
		<p>第一个段落</p>
		<p>第二个段落</p>
		<p>第三个段落</p>
		<button>向第二个 p 元素添加一个类</button>
	</body>
</html>

3.gif

【推荐学习:jQuery视频教程web前端视频

以上就是jquery怎么增加类的详细内容,更多请关注php中文网其它相关文章!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。