jquery addclass()怎么用-LMLPHP

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

在jquery中,addclass()方法用于向被选元素添加一个或多个类。

该方法不会移除已存在的 class 属性,仅仅添加一个或多个 class 属性。

提示:如需添加多个类,请使用空格分隔类名。

语法

$(selector).addClass(class)
登录后复制

也使用函数向被选元素添加类

$(selector).addClass(function(index,oldclass))
登录后复制

jquery addclass()怎么用-LMLPHP

示例:

向第一个 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").addClass("intro");
				});
			});
		</script>
		<style type="text/css">
			.intro {
				font-size: 120%;
				color: red;
			}
		</style>

	</head>

	<body>
		<h1>这是一个大标题</h1>
		<p>这是一个段落。</p>
		<p>这是另一个段落。</p>
		<button>向第一个 p 元素添加一个类</button>
	</body>

</html>
登录后复制

jquery addclass()怎么用-LMLPHP

向元素添加两个类

<!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").addClass("intro note");
				});
			});
		</script>
		<style type="text/css">
			.intro {
				font-size: 120%;
				color: blue;
			}

			.note {
				background-color: yellow;
			}
		</style>

	</head>

	<body>
		<h1>这是一个大标题</h1>
		<p>这是一个段落。</p>
		<p>这是另一个段落。</p>
		<button>向第一个 p 元素添加一个类</button>
	</body>

</html>
登录后复制

jquery addclass()怎么用-LMLPHP

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

以上就是jquery addclass()怎么用的详细内容,更多请关注Work网其它相关文章!

09-16 11:56