jQuery 如何组合多个jquery函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1250292/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:59:56  来源:igfitidea点击:

How to combine multiple jquery functions

jquery

提问by JasonDavis

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?

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

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

如果不是,我将如何将下面的代码组合成一个页面 3 次,假装它是 3 个不同的代码?

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

回答by redsquare

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 块中放入太多内容。是的,您可以拥有多个,但如果有的话,我坚持一个。您还可以将脚本放在结束正文标记之前,而无需准备好文档。

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.

我建议将代码分解为单独的函数。这样您就可以在整个页面的各个阶段重复使用它们。然后只需使用 doc ready 块来触发对该页面 init 函数的调用。

You can also use $(function(){});as a shorcut to $(document).ready(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>

回答by Randy Greencorn

I think the original poster was asking if he must do this:

我认为原始海报是在问他是否必须这样做:

<script>
 $(document).ready(function(){
        func1();
});
</script>
<script>
 $(document).ready(function(){
        func2();
});
</script>

Or if he can just do this:

或者,如果他可以这样做:

<script>
 $(document).ready(function(){
      func1();
      func2();
});
</script>

In the later example, there is one script and one document ready statement. Much cleaner. I believe the answer is yes, you can do the later without any problem.

在后面的示例中,有一个脚本和一个文档就绪语句。干净多了。我相信答案是肯定的,您可以毫无问题地进行后期操作。

回答by Tarnay Kálmán

The problem is that you don't understand what the ready event is and why you need it.

问题是您不了解就绪事件是什么以及为什么需要它。

Imagine that a page has not yet loaded fully and you try to change something on it with some javascript and since the code for that HTML element you are trying to manipulate is not even loaded yet, things go bad.

想象一下,一个页面尚未完全加载,您尝试使用一些 javascript 对其进行更改,并且由于您尝试操作的那个 HTML 元素的代码甚至还没有加载,所以事情变得很糟糕。

The ready event solves this problem. Any function (most often a single anonymous function) that you bind to the ready event gets executed as soon as all elements in the documentare ready to be traversed and manipulated. It's considered bad practice to have any inline javascript. If you want an event(click,hover,etc) to work on your page, you should call it inside the $(document).ready() function.

ready 事件解决了这个问题。一旦文档中的所有元素都准备好被遍历和操作,您绑定到ready 事件的任何函数(通常是单个匿名函数都会被执行。使用任何内联 javascript 被认为是不好的做法。如果你想让一个事件(点击、悬停等)在你的页面上工作,你应该在 $(document).ready() 函数中调用它。

And since a page only gets loaded once, any function that is bound to the ready event will only get called once. So there isn't much sense in binding multiplefunctions to the ready event. You can do everything in that one function that you bind to it. However it will cause no harm (as long as you understand what you are doing) since every function that you have bound to the ready event will be called once the DOM is ready.

由于一个页面只被加载一次,任何绑定到 ready 事件的函数只会被调用一次。所以多个函数绑定到 ready 事件没有多大意义。您可以在绑定到它的那个函数中执行所有操作。但是,它不会造成任何伤害(只要您了解自己在做什么),因为一旦 DOM 准备好,您绑定到 ready 事件的每个函数都会被调用。

I don't understand what you are trying to achieve by running that same piece of code five times... so I can't help you with that.

我不明白你想通过运行同一段代码五次来达到什么目的......所以我无法帮助你。

I hope that this explanation helps you solve your actual problem.

我希望这个解释可以帮助您解决您的实际问题。

回答by Abu Aqil

no u dont need , just put it in a single, and trigger all functions from there;

不,你不需要,只需把它放在一个单一的,并从那里触发所有功能;

<script type="text/javascript" >
 $(document).ready(function(){
        func1();
        func2();
        ...
});
</script>

回答by deceze

First of all, you can shorten that to:

首先,您可以将其缩短为:

<script type="text/javascript" >
    jQuery(function() {
        ...
    });
</script>

Second, if you want your scripts to run when the page is finished loading, then yes, you need to put them in a jQuery/document.ready()function. You can put them all in the same jQuery(function () { })block though and they'll be executed in order, you don't have to separate them.

其次,如果您希望脚本在页面加载完成后运行,那么是的,您需要将它们放在jQuery/document.ready()函数中。您可以将它们全部放在同一个jQuery(function () { })块中,它们将按顺序执行,您不必将它们分开。

To expand on the workings of function() {}blocks:

扩展function() {}块的工作原理:

jQuery(/* do something */);

means "On page load, do something". That "do something" is a function. You can pass it a function directly like this:

意思是“在页面加载时,做一些事情”。“做某事”是一个函数。你可以像这样直接传递一个函数:

function myFunction() {
    ...
}

jQuery(myFunction);

You defined a function "myFunction" and told jQuery to execute it on page load. Note that you just pass the function itself to jQuery, without (). If you'd write jQuery(myFunction());instead, that would execute myFunction()immediately, and whatever is returned by myFunction()would be placed in jQuery(), and that would be executed upon page load. It's a little different from languages like PHP, since in PHP it's desired behaviour to execute everything immediately, in Javascript that is not necessarily so. In PHP you can't pass the function itself around, in Javascript you can. Functions in Javascript act a lot more like variables.

您定义了一个函数“ myFunction”,并告诉 jQuery 在页面加载时执行它。请注意,您只是将函数本身传递给 jQuery,而没有(). 如果您jQuery(myFunction());改为编写,它将myFunction()立即执行,并且返回的任何内容myFunction()都将放置在 中jQuery(),并在页面加载时执行。它与 PHP 之类的语言略有不同,因为在 PHP 中希望立即执行所有内容,而在 Javascript 中则不一定如此。在 PHP 中你不能传递函数本身,在 Javascript 中你可以。Javascript 中的函数更像是变量。

What you usually do is "make up a function on the fly" that contains some block of code that you want executed at a later time:

您通常做的是“动态构建一个函数”,其中包含一些您希望稍后执行的代码块:

jQuery(function () {
    foo();
    bar();
});

In this case you're passing a function as well, just that you made it up on the fly and the function doesn't have a name. jQuery will hold onto this function until page load, at which time it'll execute it. Inside that function you can do as many things as you like.

在这种情况下,您还传递了一个函数,只是您在运行中创建了它并且该函数没有名称。jQuery 会保留这个函数直到页面加载,然后它会执行它。在该函数中,您可以做任意多的事情。