Home >Web Front-end >JS Tutorial >How to position the click event of a div
This article mainly talks about the positioning of div click events. Friends in need can refer to it. I hope it can help you.
Background: Multiple divs with a common className trigger the same event when clicked.
Function: The background color of the div that triggers the click event becomes red, and the background color of other divs is green.
Implementation idea: Use the $(this) keyword to obtain the div that triggers the click. First, set the background color of all current divs to green, and then set the background color of the current div to red.
About $(this): The biggest difference from this is that it is a jquery object. The same as this, it represents the current object.
<!DOCTYPE html><html> <head> <meta name="viewport" content="width=device-width, minimum-scale=1, maximum-scale=1"> <meta charset="UTF-8"> <link rel="stylesheet" href="../css/airTicket.css"> <script src="../js/jquery.min.js" ></script> <style> .div1{ background-color:#4CD964; height:20px; margin-top:10px; } </style> </head> <body> <div class="div1" id="a1">div_1</div> <div class="div1" id="a2">div_2</div> <div class="div1" id="a3">div_3</div> <div class="div1" id="a4">div_4</div> <div class="div1" id="a5">div_5</div> <script> $(function(){ $(".div1").click(function(){ var id = $(this)[0].id; conlose.log(id); $('div').css("background-color","green"); $(this).css("background-color","red"); }) }) </script> </body> </html>
The above is the detailed content of How to position the click event of a div. For more information, please follow other related articles on the PHP Chinese website!