2011-11-18 57 views
7

我有這樣的jQuery插件裏面:

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

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

    return this; 
} 

,並調用它像這樣:

$('.the-element').touchBind(function() { 
    $(this).hide(); 
}); 

我的問題是,在$(this)$(this).hide()並不是指$('.the-element'),而是DOMWindow。有什麼方法可以使這項工作?

回答

5

變化func();func.call(this);$.proxy(func, this)();

你也可以使用apply()bind()(僅限瀏覽器的支持,$.proxy()本質上是做同樣的事情)(當call()服沒有必要)。

0

如何:

$('.the-element').touchBind(function() { 
    $('.the-element').hide(); 
}); 
+1

我知道我可以做到這一點,它只是不像一個正常的jQuery插件。我喜歡能夠使用'$(this)'。 – clem

0

@Alex是正確的,您需要的僅僅是將func();替換爲func.call(this);,它將起作用。不過,我想指出的是,你在你的插件使得jQuery的構造2個冗餘呼叫:

$.fn.touchBind = function(func) { 

    //this already refers to a jQuery object 
     this.live('touchmove', function() { 

     //this refers to a DOM element inside here 
     $(this).addClass('dragged'); 
     }); 

     //this already refers to a jQuery object 
     this.live('touchend', function() { 

     //this refers to a DOM element inside here 
     if ($(this).hasClass('dragged') == false) { 
      func.call(this); 
     } 
     }); 

     return this; 
    } 

你可以驗證它是這樣的:

$.fn.whatIsThis = function(){ 
return "jquery" in this ? "jQuery object" : "Something else"; 
}; 

然後:

console.log($("div").whatIsThis()); 
//"jQuery object"