Emulate jQuery “on” with selector in pure javascript

前端 未结 3 1517
时光取名叫无心
时光取名叫无心 2020-12-05 19:39

I would emulate in pure javascript the main functionality of jQuery .on( events , selector , data) method.

For example

$(document).on(\'click\',\'.         


        
3条回答
  •  南笙
    南笙 (楼主)
    2020-12-05 20:29

    This is actually surprisingly simple. You're on the right track, but it's not quite there.

    Here's the functions I use:

    window.addEvent = function(elem,type,callback) {
        var evt = function(e) {
            e = e || window.event;
            return callback.call(elem,e);
        }, cb = function(e) {return evt(e);};
        if( elem.addEventListener) {
            elem.addEventListener(type,cb,false);
        }
        else if( elem.attachEvent) {
            elem.attachEvent("on"+type,cb);
        }
        return elem;
    };
    window.findParent = function(child,filter,root) {
        do {
            if( filter(child)) return child;
            if( root && child == root) return false;
        } while(child = child.parentNode);
        return false;
    };
    window.hasClass = function(elem,cls) {
        if( !('className' in elem)) return;
        return !!elem.className.match(new RegExp("\\b"+cls+"\\b"));
    };
    

    The window.findParent is central to the whole thing, as you can see when I show you how to attach your desired on listener:

    window.addEvent(document.body,"click",function(e) {
        var s = window.findParent(e.srcElement || e.target,function(elm) {
            return window.hasClass(elm,"button");
        },this);
        if( s) {
            console.log("It works!");
        }
    });
    

提交回复
热议问题