jQuery 添加 $(this) 到回调
jQuery add $(this) to callback
如何在回调中的以下代码中添加$(this)
?如果我只是尝试添加它,我无法在回调函数中访问 $(this)
。
$('.example').myPlugin({
option1: hello,
option2: world,
callback: function () {
// use $(this)
}
});
编辑: 如何在回调之前在 $('.example').myPlugin({... })
中添加例如 var $this = $(this)
?
带回调的部分插件:
var base = this;
// Access to jQuery and DOM versions of element
base.$el = $(el);
base.el = el;
base.pluginName = function () {
...
// Callback
if (typeof base.options.callback === 'function') {
base.options.callback.call(el);
}
...
}
将 this 的值添加到范围内的变量,然后改用该变量。
您的回调函数会将此范围限定为全局上下文(即 window)。这样做是为了在您的回调函数之外获取它的句柄。
var examples = $('.example');
for(var i = 0; i < examples.length; i++)
{
var me = $(examples[i]);
me.myPlugin({
option1: hello,
option2: world,
callback: function () {
// use "me" here
}
});
}
如何在回调中的以下代码中添加$(this)
?如果我只是尝试添加它,我无法在回调函数中访问 $(this)
。
$('.example').myPlugin({
option1: hello,
option2: world,
callback: function () {
// use $(this)
}
});
编辑: 如何在回调之前在 $('.example').myPlugin({... })
中添加例如 var $this = $(this)
?
带回调的部分插件:
var base = this;
// Access to jQuery and DOM versions of element
base.$el = $(el);
base.el = el;
base.pluginName = function () {
...
// Callback
if (typeof base.options.callback === 'function') {
base.options.callback.call(el);
}
...
}
将 this 的值添加到范围内的变量,然后改用该变量。
您的回调函数会将此范围限定为全局上下文(即 window)。这样做是为了在您的回调函数之外获取它的句柄。
var examples = $('.example');
for(var i = 0; i < examples.length; i++)
{
var me = $(examples[i]);
me.myPlugin({
option1: hello,
option2: world,
callback: function () {
// use "me" here
}
});
}