举例:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> <script src="js/jquery-1.12.4.min.js"></script> <script> $(function () { $("div").mouseover(function(){ $(this).css("color","red"); }); $("div").mouseout(function () { $(this).css("color","black"); }) }) </script> </head> <body> <div>C语言中文网</div> </body> </html>预览效果如图 1 所示。
图 1:链式调用
分析:
$("div").mouseover(function(){ $(this).css("color","red"); }) $("div").mouseout(function () { $(this).css("color","black"); })上面代码,由于操作的都是
$("div")
,因此我们可以使用链式调用语法来简化代码,如下所示:
$("div").mouseover(function(){ $(this).css("color","red"); }).mouseout(function () { $(this).css("color","black"); })
在 jQuery 中,如果对同一个对象进行多种操作,则可以使用链式调用的语法。链式调用是 jQuery 中经典语法之一,不仅节省代码量,还可以提高网站的性能。
举例:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> <style type="text/css"> table,tr,td{border:1px solid silver;} td { width:40px; height:40px; line-height:40px; text-align:center; } </style> <script src="js/jquery-1.12.4.min.js"></script> <script> $(function(){ $("td").hover(function () { $(this).parent().css("background-color","silver"); },function () { $(this).parent().css("background-color","white"); }) }) </script> </head> <body> <table> <tr> <td>2</td> <td>4</td> <td>8</td> </tr> <tr> <td>16</td> <td>32</td> <td>64</td> </tr> <tr> <td>128</td> <td>256</td> <td>512</td> </tr> </table> </body> </html>默认情况下,预览效果如图 2 所示。
图 2:默认效果
当鼠标指针移到某一个单元格上时,预览效果如图 2 所示。
图 3:鼠标指针移到单元格上时的效果
分析:
$(this).parent().css("background-color","silver")上面这句代码也用到了链式调用语法,其中
$(this).parent()
表示选取当前 td 元素的父元素(tr),然后再调用 css() 方法。在使用链式调用语法时,为了照顾到代码的可读性,我们还可以把一行代码分散到几行来写,例如下面这样:
$(".content li") .removeClass("current") .eq(n) .addClass("current");
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。