addeventlistener的兼容性写法 addeventlistener的兼容性写法

addeventlistener的兼容性写法

   var addEvent = function(element,type,callback){
        if(element.addEventListener){
            element.addEventListener(type,callback,false);
        }else if(element.attachEvent){
            element.attachEvent('on' + type,callback)
        }
        
    } 
    
    window.onload = function(){
        addEvent(document.getElementById('parent'),'click',function(event){
            var event = event || window.event;
            var target = event.target || event.srcElement;
            if(target.nodeName.toLowerCase() == 'li'){
                alert(target.id);
            }
        });

}

闭包:

<!doctype html>
<title>javascript事件兼容写法</title>
<meta charset="utf-8"/>
<script type="text/javascript">
    var addEvent = (function(){
        if(document.addEventListener){
            return function(element, type,callback){
                element.addEventListener(type,callback,false);
            }
        }else{
            return function(element, type,callback){
                element.attachEvent('on' + type,callback);
            }
        }
    })();
    window.onload = function(){
        addEvent(document.getElementById('parent'),'click',function(event){
            var event = event || window.event;
            var target = event.target || event.srcElement;
            if(target.nodeName.toLowerCase() == 'li'){
                alert(target.id);
            }
        });
    }
</script>
<ul id="parent">
    <li id="test1">aaaa</li>
    <li id="test2">aaaa</li>
    <li id="test3">aaaa</li>
    <li id="test4">aaaa</li>
    <li id="test5">aaaa</li>
    <li id="test6">aaaa</li>
</ul>

分享本文至:

评论 0

挤眼 亲亲 咆哮 开心 想想 可怜 糗大了 委屈 哈哈 小声点 右哼哼 左哼哼 疑问 坏笑 赚钱啦 悲伤 耍酷 勾引 厉害 握手 耶 嘻嘻 害羞 鼓掌 馋嘴 抓狂 抱抱 围观 威武 给力
提交评论

清空信息
关闭评论