简体   繁体   English

从document.ready外部调用document.ready内部的函数

[英]Calling a function inside document.ready from outside document.ready

I have a Jquery function defined as : 我有一个Jquery函数定义为:

jQuery(document).ready(function($){
function initAutoComplete(textBox, query, isMustMatch, isAjaxAfterKeyPress)
        {
           // autocomplete logic
        }

});

I am calling this function from outside document.ready as : 我从外部document.ready调用此函数:

initAutoComplete($("#txt" + FromTo + "Country"), "WebAddr?srvList=Country&areaCd=OT&val=", true, false);

the initAutoComplete is not recognized which is correct as its inside the scope of document.ready(). initAutoComplete无法识别,因为它在document.ready()范围内是正确的。

I tried below code by hooking the function with window object : 我通过将函数与window对象挂钩来尝试以下代码:

window.initAutoComplete = function(textBox, query, isMustMatch, isAjaxAfterKeyPress)
        {  
            //autocomplete logic
        }

Now I called this function from outside document.ready as : 现在我从外部document.ready调用此函数:

initAutoComplete($("#txt" + FromTo + "Country"), "WebAddr?srvList=Country&areaCd=OT&val=", true, false);

But I am unable to fix the reference error : initAutoComplete is not recognized. 但是我无法解决参考错误:无法识别initAutoComplete。 Any help is appreciated. 任何帮助表示赞赏。 Thanks! 谢谢!

Edit: Changed reference to window to use the jQuery version as the vanilla version is not working. 编辑:更改对窗口的引用以使用jQuery版本,因为原始版本不起作用。

When you define the function on the window like: 当您在窗口上定义函数时,如下所示:

$(window).initAutoComplete = function(textBox, query, isMustMatch, isAjaxAfterKeyPress)
        {  
            //autocomplete logic
        }

Then you also need to call it on the window like so: 然后,您还需要像下面这样在窗口上调用它:

 $(window).initAutoComplete($("#txt" + FromTo + "Country"), "WebAddr?srvList=Country&areaCd=OT&val=", true, false);

The only other thing I would mention is to make sure that you calling it outside of the document.ready is in fact done after document.ready has fired. 我唯一要提到的另一件事是确保您在document.ready之外调用它,实际上是在触发document.ready之后完成的。

Check this discussion 查看此讨论

window.onload vs $(document).ready() window.onload与$(document).ready()

The order of events depends on the browser you are using. 事件的顺序取决于您使用的浏览器。 There is a subtle difference. 有细微的差别。 Read through the article and make necessary changes if possible to "onload" rather than "ready". 通读文章,并尽可能进行“ onload”(而不是“ ready”)更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM