事件代理 / 事件委托的原理: 是利用事件冒泡机制.
优点:
1, 可以大量节省内存, 减少事件注册;
2, 对后面添加的对象一样有效, 对动态的内容尤为合适.
缺点:
不能多用在一个元素上, 否则和触发不该触发的事件.
第一种方法是利用 on()
语法: on("event","selectot","data",function)
对应着 on(事件, 选择器, 后面的函数的参数, 函数)
例子:(代码自行复制)
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="UTF-8">
- <title>jQ 代理事件 / 事件委托 </title>
- <link rel="stylesheet" href="//at.alicdn.com/t/font_650701_tns4nzt0g6p9cnmi.CSS"/>
- <style>
- *{
- margin: 0;
- padding: 0;
- box-sizing: border-box;
- }
- .list{
- width: 100%;
- text-decoration: none;
- }
- .head{
- width: 100%;
- height: 30px;
- background-color: royalblue;
- color: #fff;
- text-align: center;
- line-height: 30px;
- position: relative;
- margin-bottom: 15px;
- }
- .head .icon-home{
- left: 15px;
- position: absolute;
- font-size:20px;
- }
- .head .icon-home,
- .icon-btn{
- width: 20px;
- height: 20px;
- color: #fff;
- }
- .icon-home:focus{
- border: none;
- }
- .item{
- width:100%;
- height: 30px;
- background-color: gainsboro;
- margin-bottom: 5px;
- display: table;
- line-height: 28px;
- }
- .remove{
- display: none;
- width: 50px;
- height: 100%;
- padding-left: 15px;
- }
- .icon-btn{
- border-radius: 50%;
- border: 1px solid #fff;
- line-height:18px;
- display: inline-block;
- text-align: center;
- font-size: 14px;
- background: red;
- }
- .item .message{
- width: 100%;
- height: 100%;
- display: table-cell;
- }
- </style>
- </head>
- <body>
- <div class="head"><span class="icon-home iconfont icon-jiahao"></span>jQ 事件代理 </div>
- <ul class="list">
- <li class="item"><div class="remove"><span class="icon-btn">-</span></div><div class="message"> 项目一 </div></li>
- <li class="item"><div class="remove"><span class="icon-btn">-</span></div><div class="message"> 项目二 </div></li>
- <li class="item"><div class="remove"><span class="icon-btn">-</span></div><div class="message"> 项目三 </div></li>
- <li class="item"><div class="remove"><span class="icon-btn">-</span></div><div class="message"> 项目四 </div></li>
- <li class="item"><div class="remove"><span class="icon-btn">-</span></div><div class="message"> 项目五 </div></li>
- </ul>
- <script src="http://cdn.static.runoob.com/libs/jquery/1.10.2/jquery.min.js">
- </script>
- <script>
- $(".icon-home").click(function(){
- $('.icon-home').toggle("icon-jiahao");
- $(".remove").fadeIn(500);
- })
- //jQ 事件代理 on()
- $(".list").on("click",".icon-btn",function(){
- $(this).closest(".item").remove();
- })
- </script>
- </body>
- </html>
第二种是利用 $(e.target)
例子:(代码自行复制)
总结:
两种方法都很简单, 不过要注意 on() 方法的 this 指向,$(e.target) 的 e 参数.
来源: http://www.qdfuns.com/note/48832/d894d03c5e557518c6e71d1007bc0a80.html