功能(e)和功能()之间的区别

时间:2015-12-07 19:55:56

标签: jquery

以下代码之间的重要/区别是什么? (e)最后

jQuery(document).on( 'click', '.something', function(e) {

vs.

jQuery(document).on( 'click', '.something', function() {

谢谢!

2 个答案:

答案 0 :(得分:5)

两种表达方式在技术上没有区别。 'e'引用的事件变量是可选的,更像this中的jquery表达式。您可以使用该e变量来确定某些信息,例如调用该事件的目标或任何其他属性。

jQuery(document).on( 'click', '.something', function() {
  alert(this.id); // gives you the id of the element using this
}); 

jQuery(document).on( 'click', '.something', function(e) {
   alert(e.target.id); // gives you the id of the element using event
});

在我看来,使用事件e的最大好处是,当通过this调用事件处理程序时,与document相比,它可以提供更正确的信息。

$(document).on('click',function()
{
  alert($(this).attr("id")); // id as undefined
})

$(document).on('click',function(e)
{
  alert(e.target.id); // gets the correct id
})

示例:http://jsfiddle.net/twjwuq92/

答案 1 :(得分:1)

e参数是触发的事件,即jQuery event object。两个案例event都已创建,但要访问它,我们将其作为参数传递。

// Case 1
jQuery(document).on( 'click', '.something', function(e) {
  e.which;     // Short form. This is Click Event object.
});

// Case 2
jQuery(document).on( 'click', '.something', function() {
  // There's no reference to the event that's triggered.
});
相关问题