本教程操作环境:windows7系统、jquery1.10.2版本、Dell G3电脑。
jquery增加类的两种方法
1、使用attr()
attr()可以设置被选元素的属性值,当属性为“class”时增加类。
该种方法用于之前没有类时,新增类。
示例:向第一个 p 元素添加一个类
复制代码1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<!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、使用addClass()
addClass() 方法向被选元素添加一个或多个类。
该方法不会移除已存在的 class 属性,仅仅添加一个或多个 class 属性。如需添加多个类,请使用空格分隔类名。
示例:向第二个 p 元素添加一个类
复制代码1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<!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>
登录后复制
【推荐学习:jQuery视频教程、web前端视频】
以上就是jquery怎么增加类的详细内容,更多请关注靠谱客其它相关文章!
最后
以上就是幸福音响最近收集整理的关于jquery怎么增加类的全部内容,更多相关jquery怎么增加类内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复