How to call a function within $(document).ready from outside it

匿名 (未验证) 提交于 2019-12-03 01:55:01

问题:

How do you call function lol() from outside the $(document).ready() for example:

$(document).ready(function(){     function lol(){       alert('lol');     }   });  

Tried:

$(document).ready(function(){   lol(); });

And simply:

lol();

It must be called within an outside javascript like:

function dostuff(url){   lol(); // call the function lol() thats inside the $(document).ready() }

回答1:

Define the function on the window object to make it global from within another function scope:

$(document).ready(function(){     window.lol = function(){       alert('lol');     }   });


回答2:

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 could define 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.



回答3:

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(); });


回答4:

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(function () {      fnGetContent();       });

Where fnGetContent is here:

       function fnGetContent(keyword) {             var NewKeyword = keyword.tag;             var type = keyword.type;             $.ajax({ .......


回答5:

What about the case where Prototype is installed with jQuery and we have noconflicts set for 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?



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!