jQuery事件委托代码实践详解
javascript的事件模型,采用"冒泡"模式,子元素的事件会逐级向上"冒泡",成为父元素的事件。
在需要为较多的元素绑定事件时应该使用事件委托 event delegation
javascript事件传播
html如下:
<body> <table> <tr><td id="targetTd"></td><td></td><td></td></tr> <tr><td></td><td></td><td></td></tr> </table> </body>
添加脚本:
targetTd.onclick = function (event) { console.log("Td is clicked"); }; document.body.onclick = function (event) { console.log("Body is clicked"); };
点击td targetTd,结果如下:
Td is clicked Body is clicked
使用stopPropagation可以阻止事件的传播(ie下使用cancelBubble)
eg:
targetTd.onclick = function (event) { console.log("Td is clicked"); event.stopPropagation(); }; document.body.onclick = function (event) { console.log("Body is clicked"); };
点击td targetTd,结果如下:
Td is clicked
js事件委托
如果我们想给上面的table中所有的td添加点击事件,可以通过循环绑定,或者是采用事件委托方式,如下:
document.body.onclick = function (event) { if(event.target.tagName === "TD"){ console.log(event.target.tagName+" is clicked"); } };
jQuery事件委托
jquery 事件绑定 on 方法定义如下:
.on( events [, selector ] [, data ], handler(eventObject) )
取消事件的绑定可以使用off
$(document).off("click", "td");
给td绑定点击事件可以使用:
$("td").on("click", function(e){ console.log(e.target.tagName+" is clicked"); });
加入selector参数,使用事件委托
$("table").on("click", "td", function(){ console.log(e.target.tagName+" "); });
或者:
$(document).on("click", "td", function(){ console.log(e.target.tagName+" "); });
此时事件冒泡到document或者table时会监测是否是td selector,匹配时会触发事件
相关文章
jQuery操作attr、prop、val()/text()/html()、class属性
这篇文章主要介绍了jQuery操作attr、prop、val()/text()/html()、class属性 ,本文通过实例代码给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下2019-05-05JQuery获取元素文档大小、偏移和位置和滚动条位置的方法集合
在ajax中经常需要对元素的位置进行精确的定位,此时不仅需要获取元素自身的大小位置等属性。还需要知道页面、浏览器、滚动条等的长度和宽度。2010-01-01JQuery 1.3.2以上版本中出现pareseerror错误的解决方法
最近正在做一个系统,测试组那边不停的报告bug:后台、前台各种列表报告js弹出窗错误,内容仅仅是一句“pareseerror”!2011-01-01
最新评论