jQuery 通过 .on() 方法,来将事件处理函数绑定在元素上。
简单事件绑定
// When any <p> tag is clicked, we expect to see '<p> was clicked' in the console.
$( "p" ).on( "click", function() {
console.log( "<p> was clicked" );
});
多事件绑定,但只有一个事件处理函数
// When a user focuses on or changes any input element,
// we expect a console message bind to multiple events
$( "div" ).on( "mouseenter mouseleave", function() {
console.log( "mouse hovered over or left a div" );
});
多事件绑定,不同事件处理函数
$( "div" ).on({
mouseenter: function() {
console.log( "hovered over a div" );
},
mouseleave: function() {
console.log( "mouse left a div" );
},
click: function() {
console.log( "clicked on a div" );
}
});
事件对象
$( "div" ).on( "click", function( event ) {
console.log( "event object:" );
console.dir( event );
});
将数据传递给事件处理函数
$( "p" ).on( "click", {
foo: "bar"
}, function( event ) {
console.log( "event data: " + event.data.foo + " (should be 'bar')" );
});
将事件绑定在当下还未存在的元素上
$( "ul" ).on( "click", "li", function() {
console.log( "Something in a <ul> was clicked, and we detected that it was an <li> element." );
});
绑定只执行一次的事件处理函数
通过 .one() 方法实现此种功能,该方法的参数同 .on() 类似。
// Switching handlers using the `.one()` method
$( "p" ).one( "click", function() {
console.log( "You just clicked this for the first time!" );
$( this ).click(function() {
console.log( "You have clicked this before!" );
});
});
解除事件绑定
通过 .off() 方法,解除事件绑定。
// 解除该元素绑定的所有 click 处理函数
$( "p" ).off( "click" );
// 使用处理函数的参考引用,解除特别的 click 处理函数
var foo = function() {
console.log( "foo" );
};
var bar = function() {
console.log( "bar" );
};
$( "p" ).on( "click", foo ).on( "click", bar );
// foo will stay bound to the click event
$( "p" ).off( "click", bar );