Calling a function defined inside jQuery ready from outside of it

后端 未结 3 879
你的背包
你的背包 2020-12-21 15:55

My aspx page:-

  
  

        
相关标签:
3条回答
  • You can just declare showMessage() public by putting it directly under your <script> tag. Well that turns out as bad practice actually, but it would work.

    The better solution should always be to use your own namespace. Declare an object where all of your application logic can take place.

    <script>
    var MyApp = {
        showMessage:   function(){
           // do something
        }
    };
    

    Later in your code you can access this object from everywhere with

    MyApp.showMessage();
    

    You can bring that pattern to an extend by using closures. A lot of smart people developed nice patterns for the ecmascript therefore. A good read like always is `Javascript: the good parts" by Douglas Crockford.

    var MyApp = function(){
        var my_private_data = "version 1.0.0",
            foo             = "bar";
    
         return {
            getfoo          = function(){
                 return(foo);
            },
            showMessage     = function(){
                 // do something
            }
         };
    };
    
    var app = MyApp();
    
    app.showMessage();
    

    This is all about private data and namespacing. That way no other script on your side can possibly change any date you hold within your closured object. The idea can even taken much further by creating inheritance and shared data (semi protected), but I guess this is another story.

    0 讨论(0)
  • 2020-12-21 16:36

    As far as I know, what you want to do, can't be done. So, what exactly can we do?

    I think the simpliest think would be to move showMessage outside of the ready function, and just call it from within.

    Now, if it really must be defined within that function, make it a named function:

      function calledonready()
      {
          /// stuff
          function showMessage(){ 
          /// stuff
          }
       }
    
    $(document).ready(calledonready);
    
    window.opener.document.calledonready.showMessage(); 
    
    0 讨论(0)
  • 2020-12-21 16:37

    Declare your function like this inside the document ready:

    $(document).ready(function() {
    
        window.showMessage = function() {
            //...
        };
    
    });
    

    Then you should be able to call it from the other document like this:

    window.opener.showMessage();
    

    And because it's in the global scope, you can call it from within the main document just by calling

    showMessage();
    
    0 讨论(0)
提交回复
热议问题