jQuery插件:如何将元素引用传递给回调函数?

时间:2015-10-29 22:16:46

标签: javascript jquery callback this

TL; DR:我有jQuery.myPlugin

$.fn.myPlugin = function(param, callback){
  //...which does some operations to each member of collection
  //obtained by $('.someclass').myPlugin()
  //that are represented with this variable
}

如何在插件完成工作时将 this 变量 - 单节点引用 - 传递给callback?像这样:

$.fn.myPlugin = function(param, callback){
  //...
  //...
  //when job is done:
  callback.call(this);
}
$('.someclass').myPlugin(options, function(arg){ 
  //I need arg to be this variable from plugins definition...
})

请注意,无论我传递给callback.call(somevar),somevar在执行的匿名回调函数中都不可用。

2 个答案:

答案 0 :(得分:3)

如果回调肯定是一个功能,你应该尝试

callback(this);

答案 1 :(得分:1)

//when job is done:
callback(this);

直接调用回调。或使用

//when job is done: 
callback.call(this, this); 

请参阅.call API docs