jquery怎么增加类
时间:2022-05-18 19:50
两种方法:1、用attr(),只需给class属性添加值,语法“元素对象.attr("class","类名");”。2、用addClass(),给添加一个或多个类,语法“元素对象.addClass("类名")”,若增多个类,用空格分隔类名。 本教程操作环境:windows7系统、jquery1.10.2版本、Dell G3电脑。 jquery增加类的两种方法 1、使用attr() attr()可以设置被选元素的属性值,当属性为“class”时增加类。 该种方法用于之前没有类时,新增类。 示例:向第一个 p 元素添加一个类 2、使用addClass() addClass() 方法向被选元素添加一个或多个类。 该方法不会移除已存在的 class 属性,仅仅添加一个或多个 class 属性。如需添加多个类,请使用空格分隔类名。 示例:向第二个 p 元素添加一个类 【推荐学习:jQuery视频教程、web前端视频】 以上就是jquery怎么增加类的详细内容,更多请关注gxlsystem.com其它相关文章!<!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>
<!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>