jQuery无法访问回调函数中的$(this)

问题描述:

我正在创建一个插件,它无法访问$(this).我的插件的简单概述是

I am creating a plugin and it cannot access $(this). A simple overview of my plugin is

(function($){
    $.fn.myPlugin= function(options, callback) {
        return this.each(function(){
                $(this).click(function(){
                      // some plugin works ..

                      callback();
                });
        });
    };

})(jQuery);

然后我将插件附加到

$('p').myPlugin({
      // Some options
}, function(){
      alert('first test');
      alert($(this).text());
});

在此处单击元素p时,我会收到第一个警报,但我没有收到第二个警报.

Here when the element p is clicked, i get the first alert, but i didn't get the 2nd alert.

回调函数已调用,但无法访问this. 定义或代码有问题吗?任何其他建议也将有所帮助

The callback function is called, but unable to access this. Is there any problem with the defining or with code ? any alternative suggestion will also be helpful

使用 您可以在此处查看更新的/有效的版本.

要获得更完整的概述,可以在callback中传递更多参数,例如,如果要使options可用,可以执行以下操作:

For a more complete overview here, you can pass more arguments if you want to that callback, for example if you wanted to make the options available, you could do this:

(function($){
  $.fn.myPlugin= function(options, callback) {
    return this.each(function(){
      $(this).click(function(){
        callback.apply(this, [options]);
     });
   });
 };
})(jQuery);

然后这样称呼它:

$('p').myPlugin({
    thing: "thing1"
}, function(opts){
    alert(opts.thing); //thing1
});​

您可以在这里尝试一下,只需添加所需的任何参数即可该数组,将使用这些参数调用callback():)

You can give that one a try here, just add whatever arguments you want to that array, callback() will be called with those arguments :)