如何在jQuery中添加和删除多个类
给出一个HTML元素,任务是使用JQuery在其中添加和删除多个类。
步骤:
- 首先选择要添加多个班级的元素。
- 然后使用addClass()方法向元素添加多个类,使用removeClass()方法移除多个类。
实例1:本实例使用addClass()方法将两个类color和fontWeight添加到选定的元素中。
<!DOCTYPE HTML>
<html>
<head>
<title>
How to Add and Remove multiple classes
</title>
<script src =
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js">
</script>
<style>
.color {
color: red;
}
.fontWeight {
font-weight: bold;
}
</style>
</head>
<body style = "text-align:center;">
<h1 style = "color:green;" >
GeeksForGeeks
</h1>
<p id = "GFG_UP" style = "font-size: 19px;">
</p>
<button onClick = "GFG_Fun()">
click here
</button>
<p id = "GFG_DOWN" style =
"color: green; font-size: 24px; font-weight: bold;">
</p>
<script>
('#GFG_UP').text("Click on button to add multiple"
+ " classes to this element");
function GFG_Fun() {
("#GFG_UP").addClass("color fontWeight");
$('#GFG_DOWN').text("color and fontWeight,"
+ " Both classes added");
}
</script>
</body>
</html>
输出:
- 在点击按钮之前。
- 点击该按钮后。
例2:本例使用removeClass()方法从选定的元素中删除两个类color和fontWeight。
<!DOCTYPE HTML>
<html>
<head>
<title>
How to Add and Remove multiple classes
</title>
<script src =
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js">
</script>
<style>
.color {
color: red;
}
.fontWeight {
font-weight: bold;
}
</style>
</head>
<body style = "text-align:center;">
<h1 style = "color:green;" >
GeeksForGeeks
</h1>
<p id = "GFG_UP" class = "color fontWeight"
style = "font-size: 19px;">
</p>
<button onClick = "GFG_Fun()">
click here
</button>
<p id = "GFG_DOWN" style =
"color: green; font-size: 24px; font-weight: bold;">
</p>
<script>
('#GFG_UP').text("Click on button to remove"
+ " multiple classes to this element");
function GFG_Fun() {
("#GFG_UP").removeClass("color fontWeight");
$('#GFG_DOWN').text("color and fontWeight,"
+ " Both classes removed");
}
</script>
</body>
</html>
输出:
- 在点击按钮之前。
- 点击该按钮后。
jQuery是一个开源的JavaScript库,它简化了HTML/CSS文档之间的交互,它以其 “少写多做 “的理念而广为人知。
你可以通过学习这个jQuery教程和jQuery实例,从基础开始学习jQuery。