我正在尝试使用 Jquery 创建一个快捷方式
$(el).on('mouseup touchend touchcance', function(){})
我这样做:
$.fn.tp = function(handler){
return this.each(function(){
$(this).on('mouseup touchend touchcancel',function(){
handler();
});
})}
但是当我尝试从处理程序中的“this”获取 id 时,它返回“未定义”:
$('#myDivOne').tp(function(){
alert($(this).attr('id')) // show "undefined"
})
我该如何解决这个问题?
最佳答案
您的 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')
});
关于javascript - 在Jquery上创建事件,为什么没有返回 "this"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26518840/