javascript - 在Jquery上创建事件,为什么没有返回 "this"?

标签 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();
     });
})}

但是当我尝试从处理程序中的“this”获取 id 时,它返回“未定义”:

$('#myDivOne').tp(function(){
    alert($(this).attr('id')) // show "undefined"
})

我该如何解决这个问题?

在这里查看:http://jsfiddle.net/0yrx2hpu/

最佳答案

您的 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

关于javascript - 在Jquery上创建事件,为什么没有返回 "this"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26518840/

相关文章:

javascript - 如何使用react-redux-forms和自定义reducer避免表单对象的奇怪嵌套

Javascript 变量声明和作用域

javascript - jquery 用 img 替换 span 并检查加载的 img

javascript - Jquery datepicker 输入普通文本和日期

javascript - 动态设置下拉菜单jquery

javascript - 如何使函数可以使用多个参数调用,因此您可以执行 f(x,y) 而不是 f(x)(y)

javascript - Easel JS 的函数

javascript - 如何判断所有可见图 block 何时已满载?

javascript - 相当于 Node.js 中的 laravel 风格的服务提供者(或 wp 风格的插件)

events - 通知子组件有关 Angular2 的更改