Javascript 如何从外部调用 $(document).ready 中的函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2379529/
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
How to call a function within $(document).ready from outside it
提问by Marcus Showalter
How do you call function lol() from outside the $(document).ready() for example:
你如何从 $(document).ready() 外部调用函数 lol() 例如:
$(document).ready(function(){
function lol(){
alert('lol');
}
});
Tried:
尝试:
$(document).ready(function(){
lol();
});
And simply:
简单地说:
lol();
It must be called within an outside javascript like:
它必须在外部 javascript 中调用,例如:
function dostuff(url){
lol(); // call the function lol() thats inside the $(document).ready()
}
回答by nicerobot
Define the function on the window object to make it global from within another function scope:
在 window 对象上定义函数,使其在另一个函数范围内成为全局的:
$(document).ready(function(){
window.lol = function(){
alert('lol');
}
});
回答by cletus
Outside of the block that function is defined in, it is out of scope and you won't be able to call it.
在定义函数的块之外,它超出了范围,您将无法调用它。
There is however no need to define the function there. Why not simply:
然而,不需要在那里定义函数。为什么不简单:
function lol() {
alert("lol");
}
$(function() {
lol(); //works
});
function dostuff(url) {
lol(); // also works
}
You coulddefine the function globally like this:
您可以像这样全局定义函数:
$(function() {
lol = function() {
alert("lol");
};
});
$(function() {
lol();
});
That works but not recommended. If you're going to define something in the global namespace you should use the first method.
这有效但不推荐。如果你要在全局命名空间中定义一些东西,你应该使用第一种方法。
回答by Scott Selby
You don't need and of that - If a function is defined outside of Document.Ready - but you want to call in it Document.Ready - this is how you do it - these answer led me in the wrong direction, don't type function again, just the name of the function.
你不需要——如果一个函数是在 Document.Ready 之外定义的——但你想在它里面调用 Document.Ready——这就是你的方式——这些答案把我引向了错误的方向,不要再次输入函数,只是函数的名称。
$(document).ready(function () {
fnGetContent();
});
Where fnGetContent is here:
fnGetContent 在哪里:
function fnGetContent(keyword) {
var NewKeyword = keyword.tag;
var type = keyword.type;
$.ajax({ .......
回答by Nick Craver
Short version: you can't, it's out of scope. Define your method like this so it's available:
简短版本:你不能,它超出了范围。像这样定义您的方法,使其可用:
function lol(){
alert('lol');
}
$(function(){
lol();
});
回答by Bob Brunius
What about the case where Prototype is installed with jQuery and we have noconflicts set for jQuery?
如果 Prototype 与 jQuery 一起安装并且我们没有为 jQuery 设置冲突,那么情况如何?
jQuery(document).ready(function($){
window.lol = function(){
$.('#funnyThat').html("LOL");
}
});
Now we can call lol from anywhere but did we introduce a conflict with Prototype?
现在我们可以从任何地方调用 lol 但是我们是否引入了与 Prototype 的冲突?

