jQuery 插件:如何将元素引用传递给回调函数?
jQuery plugin: how to pass element reference to callback function?
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 在执行的匿名回调函数中都不可用。
如果回调确实是一个函数,你应该试试
callback(this);
//when job is done:
callback(this);
直接调用回调。或使用
//when job is done:
callback.call(this, this);
参见 .call
API docs。
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 在执行的匿名回调函数中都不可用。
如果回调确实是一个函数,你应该试试
callback(this);
//when job is done:
callback(this);
直接调用回调。或使用
//when job is done:
callback.call(this, this);
参见 .call
API docs。