从匿名jQuery函数中访问$(this)

时间:2011-12-30 23:12:17

标签: jquery

我正在寻找一种为jQuery实现自定义“enterKey”事件的方法:

$('selector').enterKey(function(){  
    alert( $(this).val() ) // doesn't work
});

我做过与https://stackoverflow.com/a/5689145/1123630类似的事情 它有一个例外:我无法从我的匿名函数

中访问$(this)

我想要的简化版本:

$.fn.test = function( ev ) {
    ev();
}

$('#val').test( function(){
     alert( $(this).val() );   // works well with static text, 
                               //but not with "this" pointer
});

任何帮助都是apreciated

1 个答案:

答案 0 :(得分:7)

您拨打ev的方式,this将引用全局对象(浏览器中为window)。 MDN has a nice summary about this.

您必须使用call [MDN]apply [MDN]明确设置this,或者只是将回调传递给each [docs]

$.fn.test = function( ev ) {
    return this.each(ev);
};

使用each,确保您传递的回调中的this仅引用一个 DOM元素,就像其他回调一样,就像您传递的那样到.click()

否则,在插件方法中,this引用所有选定的元素。所以这将是错误(或者至少与典型的jQuery回调不同):

$.fn.test = function( ev ) {
    ev.call(this);
    return this;
};

另一方面,这也没关系,但是不必要地冗长:

$.fn.test = function( ev ) {
    return this.each(function() {
        ev.call(this);
    });
};

如果您想将自定义参数传递给回调(ev),则必须执行此操作,否则ev会收到与each回调相同的参数。