illustrate:
Click a paragraph of text and change the text to red. After clicking again, the text will turn back to black.
The code copy is as follows:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>jquery test</title>
<script src="jquery-1.11.1.min.js"></script>
<style type="text/css">
.red
{
color:red;
}
</style>
</head>
<body>
<p>Learning is like sailing against the current, if you don't advance, you will retreat</p>
<p>Learning is like sailing against the current, if you don't advance, you will retreat</p>
<p>Learning is like sailing against the current, if you don't advance, you will retreat</p>
<p>Learning is like sailing against the current, if you don't advance, you will retreat</p>
<script type="text/javascript">
$("p").click(function(){
if($(this).hasClass("red")){ //Judge whether it has this class
$(this).removeClass("red");
}else{
$(this).addClass("red");
}
})
</script>
</body>
</html>
Because this is a process of alternating classes, you can use the toggleClass method. If the corresponding class: "red" exists, it will be removed. If it does not exist, it will be added.
The code copy is as follows:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>jquery test</title>
<script src="jquery-1.11.1.min.js"></script>
<style type="text/css">
.red
{
color:red;
}
</style>
</head>
<body>
<p>Learning is like sailing against the current, if you don't advance, you will retreat</p>
<p>Learning is like sailing against the current, if you don't advance, you will retreat</p>
<p>Learning is like sailing against the current, if you don't advance, you will retreat</p>
<p>Learning is like sailing against the current, if you don't advance, you will retreat</p>
<script type="text/javascript">
$("p").click(function(){
$(this).toggleClass("red");
})
</script>
</body>
</html>