This article summarizes the usage of events in jQuery in detail with examples, which is a good reference value for learning jQuery. Share it with everyone for your reference. The specific usage is as follows:
1. Bind events to elements through method names:
$('li').click(function(event){})
2. Bind events to elements through the bind method:
$('li') .bind('click',function(event){}) .bind('click',function(event){})
It can be seen that through bind, multiple events can be bound to elements.
3. Event namespace
Why do you need an event namespace?
→Suppose, first bind 2 click events to the li element.
$('li') .bind('click',function(event){}) .bind('click',function(event){})
→Now we need to log out one of the click events, which may be written like this:
$('li').unbind('click')
But in this way, all click events in our li are logged out, which is not what we want. Using the event namespace can solve this problem. The reason why the event namespace is needed is because it provides convenience for us when logging off events.
How to use event namespace?
→When binding an event to an element, add the namespace after the event name, conforming to the format: event name.namespace name.
$('li') .bind('click.editMode',function(event){}) .bind('click.displayMode',function(event){})
→When logging out of an event, you can write like this:
$('li').unbind('click.editMode')
4. Types of events
blur
change
click
dblclick
error
focus
focusin
focusout
keydown
keypress
keyup
load
mousedown
mouseenter
mouseleave
mousemove
mouseout
moseover
mouseup
ready
resize
scroll
select
submit
unload
5.one method
Used to create a one-time event. Once this event is executed once, it will be automatically deleted.
$("p").one("click",function(){ $(this).animate({fontSize: "+=6px"}); })
6. Delete events
//先给元素添加事件 $("p").click(function(){ $(this).slideToggle(); }) //再把元素的事件删除 $("button").click(function(){ $("p").unbind(); })
7.Event attribute
Actually, it is a global property of jquery, jQuery.Event. Whenever an event is triggered, an Event object instance is passed to the Event Handler.
Events can be created and triggered through the Event constructor.
var e = jQueery.Event("click") jQuery("body").trigger(e);
You can even pass an anonymous object in the Event through the constructor.
var e = jQuery.Event("keydown", {keyCode : 64}); jQuery("body").trigger(e);
When used, obtain the value of the anonymous object through event.data.KeyCode.
You can pass anonymous objects in Event through the constructor of jQuery.Event. Not only that, anonymous objects can also be passed through events.
$("p").click({param1 : "Hello", param2 : "World"}, someFunction); function someFunction(event){ alert(event.data.param1); alert(event.data.param2); }
It can be seen that the key of the anonymous object can be obtained through event.data.
Through Event object instances, you can also get other aspects of information, such as:
$("p").click(function(event){ alert(event.target.nodeName); })
Above, get the name of the element that triggered the event through event.target.nodeName.
Other properties of jQuery.Event include:
altKey True if the alt key is pressed. In Mac keyboards, the alt key is marked Option
ctrKey ctrl key is pressed
shiftKey Shift key is pressed
currentTarget the current element in the bubbling stage
data
metaKey Generally the Meta key is Ctrl, but on Mac it is the Command key
The horizontal coordinate of the cursor relative to the origin of the page during pageX mouse event
pageY The vertical coordinate of the cursor relative to the origin of the page during mouse event
relatedTarget The element that the cursor leaves or enters when the mouse event is triggered
The horizontal coordinate of the cursor relative to the screen origin during screenX mouse event
screenY The vertical coordinate of the cursor relative to the origin of the screen during mouse events
result returns the most recent non-undefined value from the previous event handler
target element that triggers the event
timestamp The timestamp in milliseconds when the jQuery.Event instance was created
type event type, such as click
which If it is a keyboard event, it represents the number of the key. If it is a mouse event, it records whether the left button, middle button or right button was pressed
8.Event method
event.preventDefault() prevents default behavior
event.stopPropgation() stops "bubbling", that is, stops propagating further up the DOM
event.stopImmediatePropagation() stops further propagation of all events
event.isDefaultPrevented()
event.isPropgationStopped()
isImmediatePropgagationStopped()
9.live method and on method
This method allows us to create events for elements that don’t yet exist. The difference from the bind method is that it can bind events to all matching elements, and the settings are those elements that do not yet exist and need to be dynamically created. Moreover, the live method does not necessarily need to be placed in the $(function(){}) ready handler. After jQuery 1.7, it was changed to the on method.
$("p").on("click", function(){ alert("hello"); })
If you want to cancel event registration:
$("button").click(function(){ $("p").off("click"); })
10.trigger method
The trigger method can be used when we want to manually trigger an event bound to an element.
$("#foo").on("click",function(){ alert($(this).text()); }) $("#foo").trigger("click");
还可以在绑定事件的时候出传入形参,在trigger事件的时候传入实参。
$("#foo").on("custom", function(event, param1, param2){ alert(param1 + "\n" + param2) }) $("#foo").trigger("custom",["Custom","Event"]);
trigger触发由jQuery.Event创建的实例:
var event = jQuery.Event("logged"); event.user = "foo"; event.pass = "bar"; $("body").trigger(event);
甚至可以在trigger触发方法的时候传入匿名对象:
$("body").trigger({ type: "logged", user: "foo", pass: "bar" });
如果想停止触发事件的传播,可通过jQuery.Event实例的stopPropgation()方法,或在任何事件中返回false。
11.triggerHandler方法
triggerHandler方法与trigger方法的不同之处在于:triggerHandler方法不会执行元素的默认事件,也不会"冒泡"。
//给一个元素绑定一个focus事件 $("input").focus(function(){ $("<span>Focused</span>").appendTo("#id").fadeOut(1000); }) //用triggerHandler触发 $("#id").click(function(){ $("input").triggerHandler("focus");//不会触发focus的默认行为,即进入文本框 }) //用trigger触发 $("#id").click(function(){ $("input").trigger("focus");//同时触发foucs的默认行为和绑定行为 })
12.事件冒泡和事件委托
什么是事件冒泡?
有这么一段代码。
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <body> <div> <p><a href="#foo"><span>I am a Link!</span></a></p> <p><a href="#bar"><b><i>I am another Link!</i></b></a></p> </div> </body> </html>
现在,给该页面所有的元素绑定click事件,包括window和document。
$(function () { $('*').add([document, window]).on('click', function(event) { event.preventDefault(); console.log(this); }); });
当单击页面任何元素,单击事件会从当前元素开始,向上一级元素传播,直到最顶级元素,这里是window。
如何阻止事件冒泡?
显然,通常只希望在某个特定元素发生特定的事件,不希望事件冒泡的发生。这时候我们可以针对某个特定元素绑定事件。
$(function () { $('a').on('click', function(event) { event.preventDefault(); console.log($(this).attr('href')); }); });
以上,只为a绑定了click事件,无它。
如何有效利用事件冒泡?
在jquery中,事件委托却很好地利用了事件冒泡。
<html> <body> <div id="container"> <ul id="list"> <li><a href="http://domain1.com">Item #1</a></li> <li><a href="/local/path/1">Item #2</a></li> <li><a href="/local/path/2">Item #3</a></li> <li><a href="http://domain4.com">Item #4</a></li> </ul> </div> </body> </html>
现在,我们想给现有li中的a标签绑定事件,这样写:
$( "#list a" ).on( "click", function( event ) { event.preventDefault(); console.log( $( this ).text() ); });
但是,如果又在现有的ul中添加新的li和a,那情况又如何呢?
$( "#list" ).append( "<li><a href='http://newdomain.com'>Item #5</a></li>" );
结果,点击新添加的li中的a,什么都没有发生。那么,如何为动态添加的元素绑定事件呢?
如果我们能把事件绑定到a的父级元素,那在父级元素内生成的子级动态元素,也会有绑定事件的行为。
$( "#list" ).on( "click", "a", function( event ) { event.preventDefault(); console.log( $( this ).text() ); });
以上,我们把click事件绑定到a的父级元素id为list的ul上,on方法中的第二个参数,这里是a,是事件真正的执行者。具体过程如下:
→点击某个a标签
→根据事件冒泡,触发了a的父级元素ul的click事件
→而事件真正的执行者是a
事件委托允许我们把事件绑定到父级元素,这相当于给所有的子级元素绑定了事件,不管这个子级元素是静态的、还是动态添加的。
13.toggle方法
允许我们依次执行多个事件,当执行完最后一个事件后,再执行第一个事件。
$('img[src*=small]').toggle({ function(){}, function(){}, function(){} });
14.mouseenter和mouseleave方法
$(element).mouseenter(function(){}).mouseleave(function(){})
15.hover方法
$("p").hover(function(){ $("p").css("background-color","yellow"); },function(){ $("p").css("background-color","pink"); });
相信本文所述对大家的jQuery程序设计有一定的借鉴价值。