打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
jquery 简单学习(6)

JQuery简单学习(6)——JQuery Callback 函数

文章分类:Web前端

 

动画创造了对 callback 函数的需求。

————————————————————

jQuery 动画的问题

许多 jQuery 函数涉及动画。这些函数也许会将 speed 或 duration 作为可选参数。

例子:$("p").hide("slow")

speed 或 duration 参数可以设置许多不同的值,比如 "slow", "fast", "normal" 或毫秒。

实例

Js代码
 
  1. <html>   
  2. <head>   
  3. <script type="text/javascript" src="/jquery/jquery.js"></script>   
  4. <script type="text/javascript">   
  5. $(document).ready(function(){   
  6.   $("button").click(function(){   
  7.   $("p").hide(1000);   
  8.   });   
  9. });   
  10. </script>   
  11. </head>   
  12. <body>   
  13. <button type="button">Hide</button>   
  14. <p>This is a paragraph with little content.</p>   
  15. <p>This is another small paragraph.</p>   
  16. </body>   
  17. </html>  
 由于 JavaScript 语句(指令)是逐一执行的 - 按照次序,动画之后的语句可能会产生错误或页面冲突,因为动画还没有完成。

为了避免这个情况,您可以以参数的形式添加 Callback 函数。

————————————————————
jQuery Callback 函数
当动画 100% 完成后,即调用 Callback 函数。

典型的语法:
Js代码
 
  1. $(selector).hide(speed,callback)  
 callback 参数是一个在 hide 操作完成后被执行的函数。

错误(没有 callback)
Js代码
 
  1. <html>   
  2. <head>   
  3. <script type="text/javascript" src="/jquery/jquery.js"></script>   
  4. <script type="text/javascript">   
  5. $(document).ready(function(){   
  6.   $("button").click(function(){   
  7.   $("p").hide(2000);   
  8.   alert("The paragraph is now hidden");   
  9.   });   
  10. });   
  11. </script>   
  12. </head>   
  13. <body>   
  14. <button type="button">Hide</button>   
  15. <p>This is a paragraph with little content.</p>   
  16. </body>   
  17. </html>  
 正确(有 callback)
Js代码
 
  1. <html>   
  2. <head>   
  3. <script type="text/javascript" src="/jquery/jquery.js"></script>   
  4. <script type="text/javascript">   
  5. $(document).ready(function(){   
  6.   $("button").click(function(){   
  7.   $("p").hide(1000,function(){   
  8.     alert("The paragraph is now hidden");   
  9.     });   
  10.   });   
  11. });   
  12. </script>   
  13. </head>   
  14. <body>   
  15. <button type="button">Hide</button>   
  16. <p>This is a paragraph with little content.</p>   
  17. </body>   
  18. </html>  
 结论:如果您希望在一个涉及动画的函数之后来执行语句,请使用 callback 函数。
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
JQuery简单学习(2)——JQuery语法
jQuery中的end()方法
JavaScript|jQuery基础语法
jQuery效果
jQuery框架学习第七天:jQuery动画–jQuery让页面动起来! - 学IT网 x...
js中回调函数的学习笔记
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服