jQuery 如何在 $(document).ready 中调用函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17567176/
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 19:19:29  来源:igfitidea点击:

How to call a function inside $(document).ready

jquerydebuggingfirebug

提问by IEnumerable

Im trying to debug my web app that uses jQuery.

我正在尝试调试我使用的网络应用程序 jQuery.

In firebug im calling functions inside the $(document).ready..

在萤火虫中,我正在调用 $(document).ready 中的函数。

 function val() { console.log('validated outside doc.ready'); }
 $(document).ready(function()
 {

    console.log('document ready...');

    function validate() { console.log('validated!'); }
 }

In firebug console I type validate()and it says its not a function

在萤火虫控制台我输入validate()它说它不是一个功能

If i type val()it works fine.

如果我输入val()它工作正常。

How do i call validate from the console ?

我如何从控制台调用验证?

回答by anmarti

You are not calling a function like that, you just definethe function.

你不是在调用这样的函数,你只是定义了函数。

The correct approach is to define the function outside document.readyand call it inside:

正确的做法是在外面定义函数document.ready,在里面调用:

// We define the function
function validate(){
  console.log('validated!');
}

$(document).ready(function(){
  // we call the function
  validate();
});

Another option is to self invokethe function like that:

另一种选择是像这样自调用函数:

$(document).ready(function(){
   // we define and invoke a function
   (function(){
     console.log('validated!');
   })();
});

回答by Tim

Your validatefunction is local to the function you've passed to the jQuery readyhandler.

您的validate函数是您传递给 jQueryready处理程序的函数的本地函数。

if you do:

如果你这样做:

window.validate = function(){ /*....*/ };

you will be able to access from console. But it's not good practice to pollute the global scope unless it's just for debugging.

您将能够从控制台访问。但是污染全局范围并不是一个好习惯,除非它只是为了调试。

回答by monxas

well, is there any reason you'd need that function inside document ready? only inside those brackets (scope) the function will exist. just move it out, or all it only inside document.ready

那么,您是否有任何理由需要准备好文档中的该功能?只有在这些括号(范围)内,函数才会存在。只需将其移出,或全部仅在 document.ready 中