2011-12-30 121 views
2

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

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

我已经做了类似的东西https://stackoverflow.com/a/5689145/1123630 ,并与工作一个例外:我无法将匿名函数内访问$(本)从

的我想要的简化版:

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

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

任何帮助将是aprec iated

回答

7

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

你必须明确地设置this,用call[MDN]apply[MDN],或只是通过回调each[docs]

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

使用each,您确保this回调中传递仅指one 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回调函数相同的参数。

+0

谢谢。我很惊讶,我错过了这一点。 – Liviuge 2011-12-30 23:20:16

+1

演示:http://jsfiddle.net/LbzKX/ – 2011-12-30 23:20:38

+0

对于记录良好的答案+1 – Chad 2011-12-30 23:22:46