我试图用Jquery
创建一个快捷方式$(el).on('mouseup touchend touchcance', function(){})
我这样做:
$.fn.tp = function(handler){
return this.each(function(){
$(this).on('mouseup touchend touchcancel',function(){
handler();
});
})}
但是当我试图从#34;这个"在我的处理程序中它返回" undefined":
$('#myDivOne').tp(function(){
alert($(this).attr('id')) // show "undefined"
})
我该如何解决?
答案 0 :(得分:1)
你有一个function() {}
太多了。实际上,this
是window
对象。以下应该这样做:
$.fn.tp = function(handler){
return this.each(function(){
$(this).on('mouseup touchend touchcancel',handler);
})
}
或者,您可以将this
传递给handler
,但您必须在另一端明确别名:
$.fn.tp = function(handler){
return this.each(function(){
$(this).on('mouseup touchend touchcancel',function(){
handler($,this)
});
})
}
// my event on DIV 1
$('#myDivOne').tp(function($,that){
alert($(that).attr('id')+' clicked')
});