jQuery $(this)在一个插件函数中

cle*_*lem 7 jquery this jquery-plugins

我有这个jQuery插件:

$.fn.touchBind = function(func) {
  $(this).live('touchmove', function() {
    $(this).addClass('dragged');
  });

  $(this).live('touchend', function() {
    if ($(this).hasClass('dragged') == false) {
      func();
    }
  });

  return this;
}
Run Code Online (Sandbox Code Playgroud)

并称之为:

$('.the-element').touchBind(function() {
  $(this).hide();
});
Run Code Online (Sandbox Code Playgroud)

我的问题是,$(this)$(this).hide()没有指向$('.the-element'),而是DOMWindow.有没有办法让这项工作成功?

ale*_*lex 5

更改func();func.call(this);$.proxy(func, this)();.

您也可以使用apply()(在call()诉讼时不必要)或bind()(有限的浏览器支持,$.proxy()基本上是相同的事情).