【问题标题】:jQuery plugin call function from functionjQuery插件从函数调用函数
【发布时间】:2012-10-16 15:52:15
【问题描述】:

如何从同一个对象内部调用 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() {...

【问题讨论】:

  • 你不需要将this包裹在$()中,它已经是一个jQuery对象了。
  • 您能否详细说明this 应该是什么以及您想调用什么,按什么顺序?

标签: jquery jquery-plugins call


【解决方案1】:

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

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

要确保 myMethod 与所有其他人具有相同的上下文,您可以这样做:

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

关于call()here的更多详情。

一个 JS Fiddle here.

【讨论】:

  • 谢谢,它工作正常。有什么方法可以在不通过“调用”发送的情况下到达 DOM 节点。
  • 我想一个答案可能是将methods 中的每个函数更改为始终要求jQuery 对象是第一个参数,并更改methods[method].apply(this, ...) 行以确保第一个参数也是@ 987654333@(jQuery 对象),那么您可以使用jQuery.each 获得可用的 DOM 节点集合。另一种方法是使用$.proxy...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多