jQuery事件用法实例汇总(2)
event.preventDefault()阻止默认行为
event.stopPropgation()停止"冒泡",即停止沿着DOM向上进一步传播
event.stopImmediatePropagation()停止所有事件的进一步传播
event.isDefaultPrevented()
event.isPropgationStopped()
isImmediatePropgagationStopped()
9.live方法和on方法
该方法允许我们为还不存在的元素创建事件。与bind方法不同的是:能为所有匹配的元素绑定事件,设置是那些暂时还不存在、需要动态创建的元素。而且,live方法不一定要放在$(function(){})就绪处理器中。到了 jQuery 1.7以后,就改为on方法了。
$("p").on("click", function(){ alert("hello"); })
如果想取消注册事件:
$("button").click(function(){ $("p").off("click"); })
10.trigger方法
当我们想手动触发元素绑定的事件时可以使用trigger方法。
$("#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() ); });