0

如何从同一个对象内部调用 jQuery 插件的函数。我使用确切的建议解决方案http://docs.jquery.com/Plugins/Authoring#Plugin_Methods。从外部代码我可以这样调用:

$('div').tooltip("myMethod", an_attr);

但是当'this'不是插件的对象时,我怎么能从内部特别是表单事件中调用它。

var methods = {
    var $this = $(this);
    init : function( options ) {
        $this.click(function(){
            $this.fn2("myMethod", an_attr); //is it right way?

        });
    },
    fn2 : function() {
        //but how can I call the myMethod. here ?
    },
    myMethod : function() {...
4

1 回答 1

1

fn2调用中myMethod,您可以执行以下操作:

...
fn2: function() {
  methods.myMethod();
}
...

为确保myMethod与其他所有内容具有相同的上下文,您可以执行以下操作:

...
fn2: function() {
  methods.myMethod.call(this);
}
...

更多细节在call() 这里

这里有一个 JS Fiddle 。

于 2012-10-16T16:21:35.650 回答