事件冒泡的应用——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{width:500px; height: 500px; overflow: hidden; border: 1px solid #ddd; float: left; }
        .item{width: 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>

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

posted @ 2016-09-01 21:08  marunzhou  阅读(1460)  评论(0编辑  收藏  举报