jQuery Direct and delegated events 直接事件与委托事件
2017-04-30 19:08
351 查看
ref: http://api.jquery.com/on/
直接事件: 将事件委托直接绑定到dom元素上,当事件发生时触发handler.
委托事件: 将事件委托绑定到dom元素的外层容器上,当事件发生时,冒泡到匹配的外层元素,触发相应handler.
采用委托事件的优势有2点: 1.效率高。对子元素数量非常多时,只需要绑定一个handler到父容器。 2. 可以对事件绑定调用时,尚未生成的子元素,仍然有效(只需要保证父容器已存在)。
jquery 使用on方法实现事件绑定。
直接事件: 将事件委托直接绑定到dom元素上,当事件发生时触发handler.
委托事件: 将事件委托绑定到dom元素的外层容器上,当事件发生时,冒泡到匹配的外层元素,触发相应handler.
采用委托事件的优势有2点: 1.效率高。对子元素数量非常多时,只需要绑定一个handler到父容器。 2. 可以对事件绑定调用时,尚未生成的子元素,仍然有效(只需要保证父容器已存在)。
jquery 使用on方法实现事件绑定。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Test jquery on method</title> <style> div{ border:solid 1px red; margin: 10px; padding: 10px;} </style> <script src="../JsCss/jquery-1.12.4.min.js"></script> <script> /* ref: http://api.jquery.com/on/ jquery on 方法原型: .on( events [, selector ] [, data ], handler ) */ $(function () { // delegate event 委托事件 $("#btnAdd").click(function () { $("#container").append("<div class='sub-container'><b>"+new Date().getTime()+"</b></div>"); }); $("#container").on('click', '.sub-container', function(e){ alert($(this).html()); }); // direct event 直接事件 $("#btnAdd2").click(function () { $("#container2").append("<div class='sub-container'><b>"+new Date().getTime()+"</b></div>"); }); // If selector is omitted or is null, the event handler is referred to as direct or directly-bound. $("#container2 .sub-container").on('click', function(e){ alert($(this).html()); }); }); </script> </head> <body> <button id="btnAdd">Add div</button> <div id="container"> <div>无事件触发</div> <div class='sub-container'>xxx</div> </div> <button id="btnAdd2">Add div</button> <div id="container2"> <div>无事件触发</div> <div class='sub-container'>xxx</div> </div> </body> </html>
相关文章推荐
- 简单化的事件与委托 Events and Delegates simplified
- C# 中的委托和事件——http://www.tracefact.net/CSharp-Programming/Delegates-and-Events-in-CSharp.aspx
- Delegates, Events, and Anonymous Methods 委托、事件与匿名方法
- Events and Delegates(事件和委托)
- Events and Delegates(事件和委托)
- Delegates, Events, and Anonymous Methods 委托、事件与匿名方法
- C# 中的委托和事件(http://www.tracefact.net/CSharp-Programming/Delegates-and-Events-in-CSharp.aspx)
- 简单化的事件与委托 Events and Delegates simplified
- jquery 事件委托 delegate
- C#编程利器之四:委托与事件(Delegate and event)
- jQuery - Events事件 - focus响应每个匹配元素的焦点事件
- jQuery事件委托( bind() \ live() \ delegate()) [委托 和 绑定的故事]
- C#编程利器之四:委托与事件(Delegate and event) (下)
- C#编程利器之四:委托与事件(Delegate and event) (上)
- C#/.Net中的委托(Delegates)和事件(Events) 待续。。。
- 14. 58. 20. 表格选择与监听事件 Table Selection Events and Listeners
- jQuery代码优化 事件委托篇
- 委托和事件[delegate and event]_C#
- .net的委托和事件的直接理解
- 重读C#高级编程之委托and事件