通过 jQuery,您可以把动作/方法链接起来。
Chaining 允许我们在一条语句中允许多个 jQuery 方法(在相同的元素上)。
jQuery 方法链接
直到现在,我们都是一次写一条 jQuery 语句(一条接着另一条)。
而链接(chaining)允许我们在相同的元素上运行多条 jQuery 命令,一条接着另一条。
这样的话,浏览器就不必多次查找相同的元素。
如需链接一个动作,您只需简单地把该动作追加到之前的动作上。
下面把 css(), slideUp(), and slideDown() 链接在一起,您同时也可以添加多个方法调用:
<!DOCTYPE html> <html> <head> <script src="../jquery/jquery-1.11.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>注释:本实例中 "p1" 元素首先会变为红色,然后向上滑动,然后向下滑动。
<!DOCTYPE html> <html> <head> <script src="../jquery/jquery-1.11.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 会抛掉多余的空格,并按照一行长代码来执行上面的代码行。
评论