How do I bind a click to an anchor without a framework (javascript)

前端 未结 6 601
难免孤独
难免孤独 2020-12-06 05:23

I know this is easily done in jQuery or any other framework, but that\'s not really the point. How do I go about \'properly\' binding a click event in pure javascript? I kno

6条回答
  •  再見小時候
    2020-12-06 05:37

    This is a nice cross-browser method

    var on = (function(){
        if ("addEventListener" in window) {
            return function(target, type, listener){
                target.addEventListener(type, listener, false);
            };
        }
        else {
            return function(object, sEvent, fpNotify){
                object.attachEvent("on" + sEvent, function(){
                    fpNotify(window.event);
                });
            };
        }
    }());
    
    
    on(document.getElementById("myAnchor"), "click", function(){
        alert(this.href);
    });
    

提交回复
热议问题