Home > Article > Web Front-end > Control the display and hiding of elements through jQuery
Title: Visible and invisible switching of elements through jQuery
In web development, we often encounter situations where we need to control elements by clicking buttons or other events. Visible and invisible states. This function can be easily achieved using jQuery. Next, we will use specific code examples to illustrate how to use jQuery to switch between visible and invisible elements.
First, add a button and an element that needs to control visibility in the HTML file:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>jQuery可见与不可见切换</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> </head> <body> <button id="toggleButton">切换元素可见性</button> <div id="toggleElement" style="display: none;"> 这是需要切换可见性的元素 </div> <script src="script.js"></script> </body> </html>
Next, create a new file named script.js## in the project directory # JavaScript file, write the following code:
$(document).ready(function() { $('#toggleButton').click(function() { $('#toggleElement').toggle(); }); });In this code, we first use
$(document).ready() to ensure that the code is executed after the DOM is loaded. Then listen to the click event of the button through
$('#toggleButton').click(). When the button is clicked, the
$('#toggleElement').toggle() method is called to switch the visible and invisible states of the
#toggleElement element.
#toggleElement element toggle between visible and invisible.
The above is the detailed content of Control the display and hiding of elements through jQuery. For more information, please follow other related articles on the PHP Chinese website!