0

クロスブラウザイベント追加メソッドを作成しようとしていますが、IEではまったく機能しません。コードは次のとおりです。

index.html

<!doctype html>
<html>
    <head>
    </head>

    <body>            
        <script type="text/javascript" src="helper.js"></script>
        <script type="text/javascript" src="script.js"></script>
    </body>

</html>

helper.js

var eventUtil = {

    add : function(el, type, fn){
        if(typeof(addEventListener) !== "undefined"){
            el.addEventListener(type, fn, false);
        } else if (typeof(attachEvent) !== "undefined"){
            el.attachEvent("on"+type, fn);  
        } else {
            el["on"+type] = fn;
        }
    }    
}

script.js

(function(){
    var printMsg= function(){            
        document.write("hello");
    };
    eventUtil.add(document.body, "click" , printMsg);
}());
4

1 に答える 1

2

あなたがする必要があります:

add : function(el, type, fn){
    if(typeof(el.addEventListener) !== "undefined"){
        el.addEventListener(type, fn, false);
    } else if (typeof(el.attachEvent) !== "undefined"){
        el.attachEvent("on"+type, fn);  
    } else {
        el["on"+type] = fn;
    }

あなたがそれを持っていたように:

    if(typeof(addEventListener) !== "undefined"){

それは常にグローバル変数/関数ではなく、要素のメソッドですundefinedaddEventListener

于 2012-07-21T01:37:13.930 に答える