jQuery addClass()方法
addClass()方法是jQuery的一个内置方法,用于添加更多的属性到每个选定的元素。它也可以用来改变所选元素的属性。
这种方法可以用两种不同的方式来使用。
1)通过直接添加类名:这里,类名可以直接用于将要被选中的元素。
语法:
$(selector).addClass(className);
参数:它接受参数 “className”,这是将要被添加的类的名称。
返回值:它返回带有添加的新类的选定元素。
示例 1:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src=
"https://code.jquery.com/jquery-1.10.2.js">
</script>
<title>addClass demo</title>
<style>
p {
margin: 8px;
font-size: 35px;
}
.selected {
display: block;
border: 2px solid green;
width: 160px;
height: 60px;
background-color: lightgreen;
padding: 20px;
}
.highlight {
background: yellow;
}
</style>
</head>
<body>
<p>GeeksforGeeks</p>
<p>gfg</p>
<p>CSE</p>
<script>
$("p").last().addClass("selected");
</script>
</body>
</html>
在上面的代码中,”p “元素被选中,”selected “类在jQuery的.last()方法和.addClass()方法的帮助下只应用于最后一个 “p “元素。
输出:
2)通过传递一个函数来添加一个新的类:这里,一个函数可以传递给选定元素的.addClass()。
语法:
$(selector).addClass(function);
参数:它接受一个参数 “函数”。
返回值:它返回带有附加功能的选定元素。
示例 2:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src=
"https://code.jquery.com/jquery-1.10.2.js">
</script>
<style>
div {
background: white;
margin: 20px;
}
.red {
background: red;
width: 300px;
margin: 20px;
}
.red.green {
background: lightgreen;
margin: 20px;
border: 2px solid green;
}
body {
border: 2px solid green;
width: 350px;
height: 200px;
}
</style>
</head>
<body>
<div>This div should be white</div>
<div class="red">
This div will be green because now it
has the both "green" and "red" classes.
</div>
<div>This div should be white</div>
<script>
("div").addClass(function (index, currentClass) {
var addedClass;
if (currentClass === "red") {
addedClass = "green";
("p").text("There is one green div");
}
return addedClass;
});
</script>
</body>
</html>
在上面的代码中,”div “元素被选中,在一个函数的帮助下,一个新的类被添加到选中的div元素中。
输出: