从1.7版开始,jQuery具有事件API 。这样,任何标准的javascript事件或自定义事件都可以绑定到当前选择的jQuery元素上。有诸如的快捷方式,但为您提供了更多选择。.on().click().on()
<button id="foo">bar</button>
$( "#foo" ).on( "click", function() {
console.log( $( this ).text() ); //bar
});当然,您也可以将事件与jQuery对象分离。您可以使用来实现.off( events [, selector ] [, handler ] )。
<button id="hello">hello</button>
$('#hello').on('click', function(){
console.log('hello world!');
$(this).off();
});单击该按钮时,$(this)将引用当前的jQuery对象,并从中删除所有附加的事件处理程序。您还可以指定应删除哪个事件处理程序。
$('#hello').on('click', function(){
console.log('hello world!');
$(this).off('click');
});
$('#hello').on('mouseenter', function(){
console.log('you are about to click');
});在这种情况下,mouseenter单击后事件仍将起作用。