如何结合多个jQuery功能 [英] How to combine multiple jquery functions

查看:57
本文介绍了如何结合多个jQuery功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您查看下面的jquery代码,您将看到著名的 $(document).ready(function(){),该脚本将启动脚本.我几乎在所有的jquery代码示例中都看到了这一点.网络,我想知道,如果我在一个文件中运行5个不同的代码函数,我需要在所有文件的开头使用 $(document).ready(function(){他们吗?

If you view the jquery code below you will see the famous $(document).ready(function(){ that starts the script off. I see this on pretty much all jquery code examples on the net and I am wanting to know, if I am running 5 different code functions in a single file do I need to use $(document).ready(function(){ at the beginning of all of them?

例如,如果我不怎么将下面的这段代码合并到一个页面中3次,假装它是3种不同的代码?

If not how would I combine for example this code below into a page 3 times, pretend it is 3 different codes?

<script type="text/javascript" >
 $(document).ready(function(){
  setTimeout(function(){
  $(".flash").fadeOut("slow", function () {
  $(".flash").remove();
      }); }, 2000);
 });
</script>

推荐答案

您应尽量不要在文档就绪块内放置太多内容.是的,您可以使用多个,但是如果有的话,我会坚持使用一个.您也可以将脚本放在结束body标记之前,而无需准备文档.

You should try not to put too much inside the doc ready blocks. Yes you can have multiples of them however I stick to one if any. You can also put your script just before the closing body tag without the need for document ready.

我建议将代码分成单独的功能.这样,您可以在各个阶段的整个页面中重用它们.然后,只需使用doc ready块触发对该页面init函数的调用即可.

I advise breaking the code into separate functions. That way you can reuse them throughout your page at various stages. Then just use the doc ready block to trigger a call to that pages init function.

您也可以将$(function(){});用作$(document).ready(function(){});

<script type="text/javascript" >
 $(function(){
    init();
 });

 function init(){
   someFunction();
   //other init stuff
 }

 function someFunction(){
  setTimeout(function(){
     $(".flash").fadeOut("slow", function () {
     $(".flash").remove();
   }); }, 2000);

 }
</script>

这篇关于如何结合多个jQuery功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆