Through jQuery, actions/methods can be linked. Chaining allows us to allow multiple jQuery methods (on the same element) in one statement.
Until now, we have written jQuery statements one at a time (one right after the other). However, there is a technique called chaining that allows us to run multiple jQuery commands on the same element, one right after the other. Tip: This way the browser doesn't have to look for the same element multiple times.
To link an action, you simply append the action to the previous action.
Example 1. The following example links css(), slideUp(), and slideDown() together. The "p1" element will first turn red, then slide up, then down:
<!DOCTYPE html> <html> <head> <script src="http://code.jquery.com/jquery-3.1.1.min.js"></script> <script> $(document).ready(function() { $("button").click(function(){ $("#p1").css("color","red").slideUp(2000).slideDown(2000); }); }); </script> </head> <body> <p id="p1">jQuery 乐趣十足!</p> <button>点击这里</button> </body> </html>
We can also add multiple method calls if needed. Tip: When linking, lines of code get messed up. However, jQuery is not very strict about syntax; you can write it in any format you want, including line breaks and indentation.
Example 2, it can also be run if written like this:
<!DOCTYPE html> <html> <head> <script src="http://code.jquery.com/jquery-3.1.1.min.js"></script> <script> $(document).ready(function() { $("button").click(function(){ $("#p1").css("color","red") .slideUp(2000) .slideDown(2000); }); }); </script> </head> <body> <p id="p1">jQuery 乐趣十足!</p> <button>点击这里</button> </body> </html>
jQuery will throw away extra spaces and execute the above line of code as one long line of code.