jQuery中的事件詳解
一、概述:
當(dāng)用戶與瀏覽器進(jìn)行交互時(shí)這些方法被用于注冊(cè)行為生效,并進(jìn)一步處理這些注冊(cè)行為。
二、綁定事件處理器
1、.on():
在選定的元素上綁定一個(gè)或多個(gè)事件處理函數(shù)。
on( events [, selector ] [, data ], handler(eventObject) )
Example1: 當(dāng)點(diǎn)擊段落時(shí),顯示該段落中的文本:
$("p").on("click", function(){
alert( $(this).text() );
});Example2: 向事件處理函數(shù)中傳入數(shù)據(jù),并且在事件處理函數(shù)中通過(guò)名字來(lái)獲取傳入的數(shù)據(jù):
function myHandler(event) {
alert(event.data.foo);
}
$("p").on("click", {foo: "bar"}, myHandler)Example3: 取消表單的提交動(dòng)作,并且通過(guò)返回 false 的方法來(lái)防止事件冒泡:
$("form").on("submit", false)Example4: 通過(guò)使用 .preventDefault(),僅取消默認(rèn)的動(dòng)作。
$("form").on("submit", function(event) {
event.preventDefault();
});Example5: 通過(guò)使用 .stopPropagation(),防止提交事件的冒泡行為,但是并不禁止提交行為。
$("form").on("submit", function(event) {
event.stopPropagation();
});Example6: 添加并觸發(fā)自定義事件(非瀏覽器事件)。
$("p").on("myCustomEvent",function(event,myName){
$(this).text(myName+",hithere!");
$("span")
.stop()
.css("opacity",1)
.text("myName="+myName)
.fadeIn(30)
.fadeOut(1000);
});
$("button").click(function(){
$("p").trigger("myCustomEvent",["John"]);
});Example7: 使用 對(duì)象 同時(shí)添加多個(gè)事件處
$("div.test").on({
click: function(){
$(this).toggleClass("active");
},
mouseenter: function(){
$(this).addClass("inside");
},
mouseleave: function(){
$(this).removeClass("inside");
}
});2、.one():
為元素的事件添加處理函數(shù)。處理函數(shù)在每個(gè)元素上每種事件類型最多執(zhí)行一次。
- .one( events [, data ], handler(eventObject) )
- .one( events [, selector ] [, data ], handler(eventObject) )
Example1: 為每個(gè) div 綁定一次性 click 事件。
var n = 0;
$( "div" ).one( "click", function() {
var index = $( "div" ).index( this );
$( this ).css({
borderStyle: "inset",
cursor: "auto"
});
$( "p" ).text( "Div at index #" + index + " clicked." +
" That's " + (++n) + " total clicks." );
});Example2: 在每個(gè)段落上第一次點(diǎn)擊時(shí),顯示該段落的內(nèi)容:
$( "p" ).one( "click", function() {
alert( $( this ).text() );
});Example3: 處理函數(shù)在每個(gè)元素上每種事件類型只執(zhí)行一次。
var n = 0;
$(".target").one("click mouseenter", function() {
$(".count").html(++n);
});3、.off():
移除一個(gè)事件處理函數(shù)。
.off( events [, selector ] [, handler(eventObject) ] )
Example1: 為有顏色的按鈕添加并移除事件處理。
function flash() {
$( "div" ).show().fadeOut( "slow" );
}
$( "#bind" ).click(function() {
$( "body" )
.on( "click", "#theone", flash )
.find( "#theone" )
.text( "Can Click!" );
});
$( "#unbind" ).click(function() {
$( "body" )
.off( "click", "#theone", flash )
.find( "#theone" )
.text( "Does nothing..." );
});Example2: 移除所有段落上的事件:
$( "p" ).off();
Example3: 移除所有段落上的代理事件:
$( "p" ).off( "click", "**" );
Example4: 通過(guò)傳入的第三個(gè)參數(shù),僅移除先前綁定的事件處理函數(shù):
var foo = function() {
// Code to handle some kind of event
};
// ... Now foo will be called when paragraphs are clicked ...
$( "body" ).on( "click", "p", foo );
// ... Foo will no longer be called.
$( "body" ).off( "click", "p", foo );Example5: 通過(guò)指定名字空間,解除綁定表單上所有的代理事件:
var validate = function() {
// Code to validate form entries
};
// Delegate events under the ".validator" namespace
$( "form" ).on( "click.validator", "button", validate );
$( "form" ).on( "keypress.validator", "input[type='text']", validate );
// Remove event handlers in the ".validator" namespace
$( "form" ).off( ".validator" );4、.trigger():
觸發(fā)被選元素的指定事件類型。
.trigger( eventType [, extraParameters ] )
Example1: 點(diǎn)擊 button #2 時(shí),同時(shí)觸發(fā) button #1 的點(diǎn)擊事件。
$( "button" ).first().click(function() {
update( $( "span" ).first() );
});
$( "button" ).last().click(function() {
$( "button" ).first().trigger( "click" );
update( $( "span" ).last() );
});
function update( j ) {
var n = parseInt( j.text(), 10 );
j.text( n + 1 );
}Example2: 若要提交第一個(gè)表單但又不想使用 submit() 函數(shù),請(qǐng)嘗試如下方法:
$("form:first").trigger("submit")Example3: 若要提交第一個(gè)表單但又不想使用 submit() 函數(shù),請(qǐng)嘗試如下方法:
var event = jQuery.Event( "submit" );
$( "form" ).first().trigger( event );
if ( event.isDefaultPrevented() ) {
// Perform an action...
}Example4: 向事件中傳入任意的數(shù)據(jù):
$( "p" )
.click(function( event, a, b ) {
// When a normal click fires, a and b are undefined
// for a trigger like below a refers to "foo" and b refers to "bar"
})
.trigger( "click", [ "foo", "bar" ] );Example5: 通過(guò) event 對(duì)象,向事件中傳入任意的數(shù)據(jù):
var event = jQuery.Event( "logged" ); event.user = "foo"; event.pass = "bar"; $( "body" ).trigger( event );
Example6: 另外一種通過(guò) event 對(duì)象傳入數(shù)據(jù)的方法:
$( "body" ).trigger({
type:"logged",
user:"foo",
pass:"bar"
});5、.triggerHandler():
一個(gè)事件執(zhí)行附加到元素的所有處理程序。
.triggerHandler( eventType [, extraParameters ] )
如果您使用 .triggerHandler() 觸發(fā) focus 事件,那么它只會(huì)觸發(fā)綁定了該事件的處理函數(shù),而瀏覽器的默認(rèn) focus 動(dòng)作是不會(huì)被觸發(fā)的。
$( "#old" ).click(function() {
$( "input" ).trigger( "focus" );
});
$( "#new" ).click(function() {
$( "input" ).triggerHandler( "focus" );
});
$( "input" ).focus(function() {
$( "Focused!" ).appendTo( "body" ).fadeOut( 1000 );
});6、jQuery.proxy():
接受一個(gè)函數(shù),然后返回一個(gè)新函數(shù),并且這個(gè)新函數(shù)始終保持了特定的上下文語(yǔ)境。
- jQuery.proxy( function, context [, additionalArguments ] )
- jQuery.proxy( context, name [, additionalArguments ] )
Example1: 修改使用參數(shù)為"function, context"的jQuery.proxy()方法綁定的點(diǎn)擊事件的上下文語(yǔ)境。并且在第一次點(diǎn)擊事件執(zhí)行后,解除原先的綁定。
var me = {
type: "zombie",
test: function( event ) {
// Without proxy, `this` would refer to the event target
// use event.target to reference that element.
var element = event.target;
$( element ).css( "background-color", "red" );
// With proxy, `this` refers to the me object encapsulating
// this function.
$( "#log" ).append( "Hello " + this.type + "
" );
$( "#test" ).off( "click", this.test );
}
};
var you = {
type: "person",
test: function( event ) {
$( "#log" ).append( this.type + " " );
}
};
// Execute you.test() in the context of the `you` object
// no matter where it is called
// i.e. the `this` keyword will refer to `you`
var youClick = $.proxy( you.test, you );
// attach click handlers to #test
$( "#test" )
// this === "zombie"; handler unbound after first click
.on( "click", $.proxy( me.test, me ) )
// this === "person"
.on( "click", youClick )
// this === "zombie"
.on( "click", $.proxy( you.test, me ) )
// this === "element"
.on( "click", you.test );Example2: 通過(guò)調(diào)用參數(shù)為"context, function name"的jQuery.proxy()方法,強(qiáng)制修改函數(shù)的上下文語(yǔ)境。 并且在第一次點(diǎn)擊事件執(zhí)行后,解除綁定。
var obj = {
name: "John",
test: function() {
$( "#log" ).append( this.name );
$( "#test" ).off( "click", obj.test );
}
};
$( "#test" ).on( "click", jQuery.proxy( obj, "test" ) );Example3: 更改綁定點(diǎn)擊處理程序函數(shù)的上下文。
var me = {
// I'm a dog
type: "dog",
// Note that event comes *after* one and two
test: function( one, two, event ) {
$( "#log" )
// `one` maps to `you`, the 1st additional
// argument in the $.proxy function call
.append( "Hello " + one.type + ":")// The `this` keyword refers to `me`
// (the 2nd, context, argument of $.proxy)
.append( "I am a " + this.type + ", " )
// `two` maps to `they`, the 2nd additional
// argument in the $.proxy function call
.append( "and they are " + two.type + "." )
// The event type is "click"
.append( "Thanks for " + event.type + "ing." )
// The clicked element is `event.target`,
// and its type is "button"
.append( "the " + event.target.type + "." );
}
};
var you = { type: "cat" };
var they = { type: "fish" };
// Set up handler to execute me.test() in the context
// of `me`, with `you` and `they` as additional arguments
var proxy = $.proxy( me.test, me, you, they );
$( "#test" )
.on( "click", proxy );三、瀏覽器事件
1、.resize():
為 JavaScript 的 "resize" 事件綁定一個(gè)處理函數(shù),或者觸發(fā)元素上的該事件。
.resize( [eventData ], handler(eventObject) )
當(dāng)窗口大小改變時(shí)(或改變后),查看窗口的寬度:
$(window).resize(function() {
$('body').prepend('' + $(window).width() + '');
});2、.scroll():
為 JavaScript 的 "scroll" 事件綁定一個(gè)處理函數(shù),或者觸發(fā)元素上的該事件。
.scroll( [eventData ], handler(eventObject) )
在頁(yè)面滾動(dòng)時(shí)觸發(fā)一系列動(dòng)作:
$("p").clone().appendTo(document.body);
$("p").clone().appendTo(document.body);
$("p").clone().appendTo(document.body);
$(window).scroll(function () {
$("span").css("display", "inline").fadeOut("slow");
});四、文檔加載
1 .ready(handler)
返回: jQuery:當(dāng)DOM準(zhǔn)備就緒時(shí),指定一個(gè)函數(shù)來(lái)執(zhí)行。
可以在同一個(gè)頁(yè)面中無(wú)限次地使用$(document).ready()事件。其中注冊(cè)的函數(shù)會(huì)按照(代碼中的)先后順序依次執(zhí)行。
顯示當(dāng)DOM加載的信息。
ready() 方法通常用于一個(gè)匿名函數(shù):
$( document ).ready(function() {
// Handler for .ready() called.
});代碼:
$(function() {
$("p" ).text( "The DOM is now loaded and can be manipulated." );
});2、$.holdReady():
暫停或恢復(fù).ready() 事件的執(zhí)行。
延遲就緒事件,直到已加載的插件。
$.holdReady( true );
$.getScript( "myplugin.js", function() {
$.holdReady( false );
});3、$.ready:
一個(gè)類似于promise的對(duì)象(或“thenable”),它在文檔準(zhǔn)備好時(shí)解析。
ready(), 它就是使用了這個(gè)對(duì)象。
Example1:使用jQuery.when監(jiān)聽(tīng)準(zhǔn)備好的文檔。
$.when( $.ready ).then(function() {
// Document is ready.
});Example2:典型的用法涉及到另一個(gè)promise,使用jQuery.when。
$.when(
$.getJSON( "ajax/test.json" ),
$.ready
).done(function( data ) {
// Document is ready.
// Value of test.json is passed as `data`.
});五、表單事件
1、.blur():
為 "blur" 事件綁定一個(gè)處理函數(shù),或者觸發(fā)元素上的 "blur" 事件(注:此事件不支持冒泡)。
2、.change( [eventData ], handler )
為JavaScript 的 "change" 事件綁定一個(gè)處理函數(shù),或者觸發(fā)元素上的 "change" 事件。
Example1: 為 select 元素添加 change 事件,將選中的項(xiàng)目顯示在 div 中。
$("select").change(function () {
var str = "";
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
$("div").text(str);
})
.change();Example2: 所有文本輸入元素添加一個(gè)的有效性測(cè)試:
$("input[type='text']").change( function() {
// check input ($(this).val()) for validity here
});3、其他表單事件
- .focus():為 JavaScript 的 "focus" 事件綁定一個(gè)處理函數(shù),或者觸發(fā)元素上的 "focus" 事件。
- .focusin():將一個(gè)事件函數(shù)綁定到"focusin" 事件。
- .focusout():將一個(gè)事件函數(shù)綁定到"focusout" 事件。
- .select():為 JavaScript 的 "select" 事件綁定一個(gè)處理函數(shù),或者觸發(fā)元素上的該事件。
- .submit():為 JavaScript 的 "submit" 事件綁定一個(gè)處理函數(shù),或者觸發(fā)元素上的該事件。
.submit( [eventData ], handler(eventObject) )
Example1: 如果你想根據(jù)一個(gè)標(biāo)識(shí)來(lái)阻止表單被提交的話,可以像下面這樣做:
$("form").submit(function() {
if ($("input:first").val() == "correct") {
$("span").text("Validated...").show();
return true;
}
$("span").text("Not valid!").show().fadeOut(1000);
return false;
});Example2: 如果你想根據(jù)一個(gè)標(biāo)識(shí)來(lái)阻止表單被提交的話,可以像下面這樣做:
$("form").submit( function () {
return this.some_flag_variable;
} );Example3: 觸發(fā)頁(yè)面上第一個(gè)表單的提交事件:
$("form:first").submit();六、鍵盤(pán)事件
- .keydown():為 "keydown" 事件綁定一個(gè)處理函數(shù),或者觸發(fā)元素上的 "keydown" 事件。
- .keypress():為 "keypress" 事件綁定一個(gè)處理函數(shù),或者觸發(fā)元素上的 "keypress" 事件。
- .keyup():為 "keyup" 事件綁定一個(gè)處理函數(shù),或者觸發(fā)元素上的 "keyup" 事件。
.keyup( [eventData ], handler(eventObject) )
當(dāng)在文本框中松開(kāi)一個(gè)按鍵時(shí),顯示 keyup 事件的 event 對(duì)象。(使用一個(gè)簡(jiǎn)單的 $.print 插件)。
var xTriggered = 0;
$('#target').keyup(function(event) {
xTriggered++;
var msg = 'Handler for .keyup() called ' + xTriggered + ' time(s).';
$.print(msg, 'html');
$.print(event);
}).keydown(function(event) {
if (event.which == 13) {
event.preventDefault();
}
});
$('#other').click(function() {
$('#target').keyup();
});七、鼠標(biāo)事件
1、.click():
為 JavaScript 的"click" 事件綁定一個(gè)處理器,或者觸發(fā)元素上的 "click" 事件。
.click( [eventData ], handler(eventObject) )
Example1: 點(diǎn)擊段落時(shí)隱藏他們:
$("p").click(function () {
$(this).slideUp();
});Example2: 在頁(yè)面上所有段落上觸發(fā)click事件。
$("p").click();2、其他鼠標(biāo)事件
- .contextmenu():為 JavaScript 的"contextmenu" 事件綁定一個(gè)處理器,或者觸發(fā)元素上的 "contextmenu" 事件。
- .dblclick():為JavaScript 的 "dblclick" 事件綁定一個(gè)處理函數(shù),或者觸發(fā)元素上的 "dblclick" 事件。
- .hover():將二個(gè)事件函數(shù)綁定到匹配元素上,分別當(dāng)鼠標(biāo)指針進(jìn)入和離開(kāi)元素時(shí)被執(zhí)行。將一個(gè)單獨(dú)事件函數(shù)綁定到匹配元素上,分別當(dāng)鼠標(biāo)指針進(jìn)入和離開(kāi)元素時(shí)被執(zhí)行。
- .mousedown():為 JavaScript 的 "mousedown" 事件綁定一個(gè)處理函數(shù),或者觸發(fā)元素上的該事件。
- .mouseenter():為 mouse enters(鼠標(biāo)進(jìn)入) 事件綁定一個(gè)處理函數(shù),或者觸發(fā)元素上的 mouse enters(鼠標(biāo)進(jìn)入) 事件。
- .mouseleave():為 mouse leaves(鼠標(biāo)離開(kāi)) 事件綁定一個(gè)處理函數(shù),或者觸發(fā)元素上的 mouse leaves(鼠標(biāo)離開(kāi)) 事件。
- .mousemove():為 JavaScript 的 "mousemove" 事件綁定一個(gè)處理函數(shù),或者觸發(fā)元素上的該事件。
- .mouseout():為 JavaScript 的 "mouseout" 事件綁定一個(gè)處理函數(shù),或者觸發(fā)元素上的該事件。(注:支持事件冒泡)
- .mouseover():為 JavaScript 的 "mouseover" 事件綁定一個(gè)處理函數(shù),或者觸發(fā)元素上的該事件。(注:支持事件冒泡)
- .mouseup():為 JavaScript 的 "mouseup" 事件綁定一個(gè)處理函數(shù),或者觸發(fā)元素上的該事件。
八、事件對(duì)象
1、屬性列表:
- metaKey:表示事件觸發(fā)時(shí)哪個(gè)Meta鍵被按下。
- pageX、pageY:鼠標(biāo)相對(duì)于文檔的左邊緣、頂部邊緣的位置(坐標(biāo))。
- relatedTarget:在事件中涉及的其它任何DOM元素。
- target:觸發(fā)事件的DOM元素。
- which:針對(duì)鍵盤(pán)和鼠標(biāo)事件,這個(gè)屬性能確定你到底按的是哪個(gè)鍵。
- type:描述事件的性質(zhì)。
- currentTarget:在事件冒泡過(guò)程中的當(dāng)前DOM元素。
- data:當(dāng)當(dāng)前正在執(zhí)行的處理程序綁定時(shí),一個(gè)可選的數(shù)據(jù)對(duì)象傳遞給一個(gè)事件方法。
- delegateTarget:綁定了當(dāng)前正在調(diào)用jQuery 事件處理器的元素。
- namespace:當(dāng)事件被觸發(fā)時(shí)此屬性包含指定的命名空間。
- result:事件被觸發(fā)的一個(gè)事件處理程序的最后返回值,除非值是 undefined。
- timeStamp:這個(gè)屬性返回事件觸發(fā)時(shí)距離1970年1月1日的毫秒數(shù)。
某些事件可能有它們特定的屬性。 那些屬性可以存取在event.originalEvent對(duì)象上。
// add the dataTransfer property for use with the native `drop` event // to capture information about files dropped into the browser window jQuery.event.props.push( "dataTransfer" );
2、函數(shù)列表:
- event.isDefaultPrevented():根據(jù)事件對(duì)象中是否調(diào)用過(guò) event.preventDefault() 方法,來(lái)返回一個(gè)布爾值。
- event.isImmediatePropagationStopped():根據(jù)事件對(duì)象中是否調(diào)用過(guò) event.stopImmediatePropagation() 方法,來(lái)返回一個(gè)布爾值。
- event.isPropagationStopped():根據(jù)事件對(duì)象中是否調(diào)用過(guò) event.stopPropagation() 方法,來(lái)返回一個(gè)布爾值。
- event.preventDefault():如果調(diào)用這個(gè)方法,默認(rèn)事件行為將不再觸發(fā)。
- event.stopImmediatePropagation():阻止剩余的事件處理函數(shù)執(zhí)行并且防止事件冒泡到DOM樹(shù)上。
- event.stopPropagation():防止事件冒泡到DOM樹(shù)上,也就是不觸發(fā)的任何前輩元素上的事件處理函數(shù)。
記錄按鍵:
$('#whichkey').bind('keydown',function(e){
$('#log').html(e.type + ': ' + e.which );
});到此這篇關(guān)于jQuery事件的文章就介紹到這了。希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
jquery的checkbox,radio,select等方法小結(jié)
jquery的checkbox,radio,和select是jquery操作的一個(gè)難點(diǎn)和重點(diǎn),很多前端新手對(duì)其了解不是很透徹。時(shí)間久了不用,我在寫(xiě)的時(shí)候有時(shí)也難免對(duì)某些操作支支吾吾,記不清楚,現(xiàn)在,對(duì)其做一些簡(jiǎn)單的總結(jié)2016-08-08
Jquery Easyui選項(xiàng)卡組件Tab使用詳解(10)
這篇文章主要為大家詳細(xì)介紹了Jquery Easyui菜單組件Menu的使用方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-12-12
jQuery實(shí)現(xiàn)鼠標(biāo)經(jīng)過(guò)像翻頁(yè)和描點(diǎn)鏈接效果
這篇文章主要介紹了jQuery實(shí)現(xiàn)鼠標(biāo)經(jīng)過(guò)像翻頁(yè)和描點(diǎn)鏈接效果的相關(guān)資料,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2016-08-08
jQuery 頂部導(dǎo)航跟隨滾動(dòng)條滾動(dòng)固定浮動(dòng)在頂部
這篇文章主要介紹了通過(guò)jQuery實(shí)現(xiàn)的頂部導(dǎo)航跟隨滾動(dòng)條滾動(dòng)固定浮動(dòng)在頂部,需要的朋友可以參考下2014-06-06
easyUI 實(shí)現(xiàn)的后臺(tái)分頁(yè)與前臺(tái)顯示功能示例
這篇文章主要介紹了easyUI 實(shí)現(xiàn)的后臺(tái)分頁(yè)與前臺(tái)顯示功能,結(jié)合實(shí)例形式分析了easyUI 后臺(tái)數(shù)據(jù)交互、分頁(yè)與前臺(tái)顯示相關(guān)操作技巧及注意事項(xiàng),需要的朋友可以參考下2020-06-06
jQuery插件ContextMenu自定義圖標(biāo)
這篇文章主要為大家詳細(xì)介紹了jQuery插件ContextMenu自定義圖標(biāo)的相關(guān)代碼,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-03-03

