如何从外部调用$(document).ready中的对象

时间:2015-05-31 09:02:08

标签: javascript jquery

功能如下:



(function ($) {
	$(document).ready(function () {
		var MyObject = {
			MyFunction: function(){
				alert('I am here');
			}
		}
	});
}(jQuery));

MyObject.MyFunction();




我怎样才能像上面那样打电话?

3 个答案:

答案 0 :(得分:0)

<Magazine>回调按照注册顺序调用(ref)。实现目标的一种方法是创建一个全局对象,然后在一个document.ready()中初始化它,并在随后的$(document).ready()中调用它。

&#13;
&#13;
$(document).ready()
&#13;
var MyObject = {};
(function($) {
  $(document).ready(function() {
    MyObject = {
      MyFunction: function() {
        alert('I am here');
      }
    }
  });
}(jQuery));


(function($) {
  $(document).ready(function() {
       MyObject.MyFunction();    
    });
}(jQuery));
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您的变量会在您声明它的事件之外丢失范围。

您的代码

  (function ($) {
   $(document).ready(function () {
    var MyObject = {
        MyFunction: function(){
            alert('I am here');
        }
    }
   });
  }(jQuery));

您的声明,并且在您的函数调用无法访问的其他函数定义的任何其他范围之外

var MyObject 

需要在$(文件).ready(...)

之外

答案 2 :(得分:0)

所以,你是在选项1 之后。

// Option 1: Object in a gloabl scrope
var myObject = {
    myFunction: function(){
        alert('I am here');
    }
};

(function ($) {

    // Option 2: Object in a function scope
    var myObject2 = {
        myFunction2: function(){
            alert('I am here 2');
        }
    };

    $(document).ready(function () {
        // Option 3: Object in a local (to the "(function ($) {") function scope
        var myObject3 = {
            myFunction3: function(){
                alert('I am here 3');
            }
        };

        //alerts 'I am here 2';
        myObject2.myFunction2();

        //alerts 'I am here 3';
        myObject3.myFunction3();
    });

    //alerts 'I am here 2';
    myObject2.myFunction2();

    //Uncaught TypeError: myObject3.myFunction3 is not a function - can't access a locally scoped function on a global scope
    myObject3.myFunction3();

}(jQuery));

//alerts 'I am here';
myObject.myFunction();

//Uncaught TypeError: myObject2.myFunction2 is not a function - can't access a locally scoped function on a global scope
myObject2.myFunction2();

//Uncaught TypeError: myObject3.myFunction3 is not a function - can't access a locally scoped function on a global scope
myObject3.myFunction3();