在Jquery上创建一个事件,为什么"这个"还没有退回?

时间:2014-10-22 23:26:02

标签: javascript jquery events jquery-plugins

我试图用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"
})

我该如何解决?

点击此处:http://jsfiddle.net/0yrx2hpu/

1 个答案:

答案 0 :(得分:1)

你有一个function() {}太多了。实际上,thiswindow对象。以下应该这样做:

$.fn.tp = function(handler){
    return this.each(function(){
         $(this).on('mouseup touchend touchcancel',handler);
    })
}

DEMO

或者,您可以将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')   
});

DEMO