简体   繁体   中英

Calling a function inside document.ready from outside document.ready

I have a Jquery function defined as :

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

});

I am calling this function from outside document.ready as :

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().

I tried below code by hooking the function with window object :

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

Now I called this function from outside document.ready as :

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. Any help is appreciated. Thanks!

Edit: Changed reference to window to use the jQuery version as the vanilla version is not working.

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.

Check this discussion

window.onload vs $(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".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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