简体   繁体   中英

Function calls from outside of $(document).ready to the function defined in the $(document).ready

I wanna use $(window).resize to call some function when a mobile device orientation change, I wrote all my code inside the $(document).ready, this works when I use an Android device, but with iPhone after first orientation is detected it doesn't call $(window).resize even again. When I put the (window).resize function outside of $(document).ready, it also works on iPhone.

Inside this $(window).resize function, I have to make call to the methods which are defined in the $(document).ready block, so how can I do that?

As you need to use something from two different event handlers, you should move that something out of the event handler. You can't create the methods in either event handler, because you can't know if ready or resize will be triggered first.

You can for example create an object that holds the methods:

var commonMethods = {
  data: 42,
  someMethod: function() { alert(this.data); }
};

$(document).ready(function(){
  commonMethods.someMethod();
});

$(window).resize(function(){
  commonMethods.someMethod();
});

Define your methods outside the $(document).ready() block.
Then only call them as you need them throughout the code. This way, you have access to them both from the $(document).ready() and the $(window).resize() blocks.

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