jquery的addclass()如何用

2023-05-13,

本篇内容介绍了“jquery的addclass()如何用”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

在jquery中,addclass()方法用于向被选元素添加一个或多个类,语法为“$(selector).addClass(“类名”)”;如需添加多个类,需要使用空格分隔类名。

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

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

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

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

语法

$(selector).addClass(class)

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

$(selector).addClass(function(index,oldclass))

示例:

向第一个 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>
		<h2>这是一个大标题</h2>
		<p>这是一个段落。</p>
		<p>这是另一个段落。</p>
		<button>向第一个 p 元素添加一个类</button>
	</body>

</html>

向元素添加两个类

<!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>
		<h2>这是一个大标题</h2>
		<p>这是一个段落。</p>
		<p>这是另一个段落。</p>
		<button>向第一个 p 元素添加一个类</button>
	</body>

</html>

“jquery的addclass()如何用”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注本站网站,小编将为大家输出更多高质量的实用文章!

《jquery的addclass()如何用.doc》

下载本文的Word格式文档,以方便收藏与打印。