• 事件冒泡的应用——jq on的实现


    曾对jQuery中on的实现有所疑问,一直没有找到合适的实现方法,今日看《javascript高级程序设计》中的事件冒泡有了些思路。

    针对于新增的DOM元素,JQ中若为其绑定事件就必须使用on方法,如$('#id').on('click','.item',function(){......}),这样当$('#id')被点击时,会发生事件冒泡,传递到$('#id')下的item并进行匹配,符合条件的会触发function(){.......}。

    这里写一个简单的例子演示下:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <style>
            .box{500px; height: 500px; overflow: hidden; border: 1px solid #ddd; float: left; }
            .item{ 50px;height: 50px;background: #000;color: #fff;text-align: center; }
        </style>
    </head>
    <body>
        <div class="box" id="box"></div>
        <div class="op">
            <button id="add">添加</button>
            <button id="remove">删除</button>
            <button id="copy">复制首元素</button>
            <button id="replace">替换尾元素</button>
        </div>
    </body>
    </html>
    <script>
        var i = 0,
            $ = function(id){ return document.getElementById(id); },
            ele = function(){
                var div = document.createElement('div');
                    div.className = 'item';
                    div.innerHTML = i++;
    
                return div;
            },
            // on事件,点击由item开始向上传递
            // 传递到box时,触发了box的click事件
            on = function($pele,ele,type,func){
                $pele.addEventListener(type,function(e){
                    if( e.target.className == ele ){
                        func();
                    }
                },false);
            };
        // 调用on事件
        on($('box'),'item','click',function(){alert('点击成功!')});
    
        // 添加元素
        $('add').onclick = function(){
            $('box').appendChild(ele());
        }
    
        // 移动最后一个元素
        $('remove').onclick = function(){
            $('box').removeChild($('box').lastChild);
        }
    
        // 复制首元素
        $('copy').onclick = function(){
            $('box').appendChild($('box').firstChild.cloneNode(true));
        }
    
        // 替换最后一个元素
        $('replace').onclick = function(){
            $('box').replaceChild($('box').firstChild,$('box').lastChild);
        }
    </script>

    例子写得比较粗陋,主要是验证一下思路!

  • 相关阅读:
    COJ 1691:前缀和
    COJ 1692:模拟
    POJ 3415:后缀数组+单调栈优化
    python拓展知识
    git总结
    好的文章及博客收集
    python爬虫总结
    ajax与java后台交互
    Java多线程与并发库
    Django框架创建
  • 原文地址:https://www.cnblogs.com/marunzhou/p/5831230.html
Copyright © 2020-2023  润新知