jquery中给元素增加一个类
1、使用attr()方法
attr() 方法设置或返回被选元素的属性值。
根据该方法不同的参数,其工作方式也有所差异。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="js/jquery-1.10.2.min.js"></script>
<script>
$(document).ready(function() {
$("button").click(function() {
$("p:first").attr("class","intro");
});
});
</script>
<style>
.intro {
font-size: 150%;
color: red;
}
</style>
</head>
<body>
<h1>这是一个标题</h1>
<p>这是一个段落。</p>
<p>这是另一个段落。</p>
<button>给第一个P元素添加一个类名</button>
</body>
</html>

2、使用addClass()方法
addClass() 方法向被选元素添加一个或多个类名。
该方法不会移除已存在的 class 属性,仅仅添加一个或多个类名到 class 属性。
提示:如需添加多个类,请使用空格分隔类名。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="js/jquery-1.10.2.min.js"></script>
<script>
$(document).ready(function() {
$("button").click(function() {
$("p:first").addClass("intro");
});
});
</script>
<style>
.intro {
font-size: 150%;
color: pink;
}
</style>
</head>
<body>
<h1>这是一个标题</h1>
<p>这是一个段落。</p>
<p>这是另一个段落。</p>
<button>给第一个P元素添加一个类名</button>
</body>
</html>


