发布在:事件

jQuery 事件基础

链接 jQuery 事件基础

链接 在 DOM 元素上设置事件响应

jQuery 使得在页面元素上设置事件驱动的响应变得简单。这些事件通常由最终用户与页面的交互触发,例如在表单元素中输入文本或移动鼠标指针。在某些情况下,例如页面加载和卸载事件,浏览器本身将触发事件。

jQuery 为大多数原生浏览器事件提供了便捷的方法。这些方法(包括 .click().focus().blur().change() 等)是 jQuery 的 .on() 方法的简写。on 方法对于将同一个处理程序函数绑定到多个事件、当您想向事件处理程序提供数据、当您使用自定义事件或当您想传递多个事件和处理程序的对象时非常有用。

1
2
3
4
// Event setup using a convenience method
$( "p" ).click(function() {
console.log( "You clicked a paragraph!" );
});
1
2
3
4
// Equivalent event setup using the `.on()` method
$( "p" ).on( "click", function() {
console.log( "click" );
});

链接 将事件扩展到新页面元素

需要注意的是,.on() 只能对设置监听器时存在的元素创建事件监听器。在建立事件监听器之后创建的类似元素不会自动获取您之前设置的事件行为。例如

1
2
3
4
5
6
7
8
9
10
11
12
13
$( document ).ready(function(){
// Sets up click behavior on all button elements with the alert class
// that exist in the DOM when the instruction was executed
$( "button.alert" ).on( "click", function() {
console.log( "A button with the alert class was clicked!" );
});
// Now create a new button element with the alert class. This button
// was created after the click listeners were applied above, so it
// will not have the same click behavior as its peers
$( "<button class='alert'>Alert!</button>" ).appendTo( document.body );
});

查阅事件委托文章,了解如何使用 .on(),以便将事件行为扩展到新元素,而无需重新绑定它们。

链接 在事件处理程序函数中

每个事件处理函数都会接收一个事件对象,其中包含许多属性和方法。事件对象最常用于通过 .preventDefault() 方法阻止事件的默认操作。但是,事件对象包含许多其他有用的属性和方法,包括

链接 pageX、pageY

事件发生时的鼠标位置,相对于页面显示区域的左上角(而不是整个浏览器窗口)。

链接 type

事件的类型(例如,“click”)。

链接 which

按下按钮或按键。

链接 data

绑定事件时传入的任何数据。例如

1
2
3
4
5
6
7
8
// Event setup using the `.on()` method with data
$( "input" ).on(
"change",
{ foo: "bar" }, // Associate data with event binding
function( eventObject ) {
console.log("An input value has changed! ", eventObject.data.foo);
}
);

链接 target

引发事件的 DOM 元素。

链接 namespace

触发事件时指定的命名空间。

链接 timeStamp

浏览器中事件发生时间与 1970 年 1 月 1 日之间的毫秒差。

链接 preventDefault()

阻止事件的默认操作(例如,访问链接)。

链接 stopPropagation()

阻止事件冒泡到其他元素。

除了事件对象外,事件处理函数还可以通过关键字 this 访问绑定处理程序的 DOM 元素。若要将 DOM 元素转换为我们可以对它使用 jQuery 方法的 jQuery 对象,我们只需执行 $( this ),通常遵循此惯例

1
var element = $( this );

一个更完整的示例如下

1
2
3
4
5
6
7
8
// Preventing a link from being followed
$( "a" ).click(function( eventObject ) {
var elem = $( this );
if ( elem.attr( "href" ).match( /evil/ ) ) {
eventObject.preventDefault();
elem.addClass( "evil" );
}
});

链接 设置多个事件响应

应用程序中的元素通常会绑定到多个事件。如果多个事件要共享同一个处理函数,你可以将事件类型作为以空格分隔的列表提供给 .on()

1
2
3
4
5
6
7
// Multiple events, same handler
$( "input" ).on(
"click change", // Bind handlers for multiple events
function() {
console.log( "An input was clicked or changed!" );
}
);

当每个事件都有自己的处理程序时,你可以将一个对象传递到 .on() 中,其中包含一个或多个键/值对,键是事件名称,值是处理事件的函数。

1
2
3
4
5
// Binding multiple events with different handlers
$( "p" ).on({
"click": function() { console.log( "clicked!" ); },
"mouseover": function() { console.log( "hovered!" ); }
});

链接 命名空间事件

对于复杂应用程序和与他人共享的插件,对事件进行命名空间非常有用,这样你不会无意中断开你不知道或无法了解的事件。

1
2
3
4
// Namespacing events
$( "p" ).on( "click.myNamespace", function() { /* ... */ } );
$( "p" ).off( "click.myNamespace" );
$( "p" ).off( ".myNamespace" ); // Unbind all events in the namespace

链接 移除事件监听器

要移除事件监听器,请使用 .off() 方法并传入要关闭的事件类型。如果你将一个命名函数附加到事件,那么你可以通过将它作为第二个参数传递,将事件移除操作隔离到该命名函数。

1
2
// Tearing down all click handlers on a selection
$( "p" ).off( "click" );
1
2
3
4
5
6
// Tearing down a particular click handler, using a reference to the function
var foo = function() { console.log( "foo" ); };
var bar = function() { console.log( "bar" ); };
$( "p" ).on( "click", foo ).on( "click", bar );
$( "p" ).off( "click", bar ); // foo is still bound to the click event

链接 设置仅运行一次的事件

有时你需要一个特定处理程序仅运行一次——在那之后,你可能希望没有处理程序运行,或者你可能希望运行不同的处理程序。jQuery 为此提供了 .one() 方法。

1
2
3
4
5
6
7
8
9
10
// Switching handlers using the `.one()` method
$( "p" ).one( "click", firstClick );
function firstClick() {
console.log( "You just clicked this for the first time!" );
// Now set up the new handler for subsequent clicks;
// omit this step if no further click responses are needed
$( this ).click( function() { console.log( "You have clicked this before!" ); } );
}

请注意,在上面的代码片段中,firstClick 函数将对每个段落元素执行一次点击,而不是在任何段落第一次被点击时从所有段落中移除该函数。

.one() 还可以用于绑定多个事件

1
2
3
4
5
6
// Using .one() to bind several events
$( "input[id]" ).one( "focus mouseover keydown", firstEvent);
function firstEvent( eventObject ) {
console.log( "A " + eventObject.type + " event occurred for the first time on the input with id " + this.id );
}

在这种情况下,firstEvent 函数将针对每个事件执行一次。对于上述代码段,这意味着一旦某个输入元素获得焦点,处理程序函数仍将针对该元素上的第一个 keydown 事件执行。