JavaScript addEvent函数

时间:2011-11-20 00:19:04

标签: javascript javascript-events

我有一个addEvent功能:

function addEvent(elem, event, func ) {
   if (typeof (window.event) != 'undefined')
        elem.attachEvent('on' + event, func);
   else 
       elem.addEventListener(event, func, false);
}

<a href="#" id="link">link</a>

我试图将以下内容添加到window.onload

addEvent(window, 'load', function (){
   // add another event
   var link= document.getElementById('link');
   addEvent(link, 'click', function () {alert('Hi'); });
});

我的问题是:为什么link事件不起作用?

5 个答案:

答案 0 :(得分:4)

你拼错了function

答案 1 :(得分:1)

试试这个:

function attachEvent(element, event, callbackFunction) {
    if (element.addEventListener) {
        element.addEventListener(event, callbackFunction, false);
    } else if (element.attachEvent) {
        element.attachEvent('on' + event, callbackFunction);
    }
};

答案 2 :(得分:0)

typeof (window.event) != 'undefined'
当我测试你的代码时,

在chrome上不起作用! 这样可以正常工作:

!!window.attachEvent

我认为在if..esle中使用大括号是一种很好的做法。

function addEvent(elem, event, func ) {
    if (!!window.attachEvent){

        elem.attachEvent('on' + event, func);
    }
    else{
       elem.addEventListener(event, func, false);
    }
}

答案 3 :(得分:0)

不要这样做,试试这个:

Element.prototype.events = {};
Element.prototype.addEvent = function (event, callBack) {
    if (this.events["on" + (event.replace("on", ""))] == undefined) {
        this.events["on" + (event.replace("on", ""))] = [];
    }
    this.events["on" + (event.replace("on", ""))].push(callBack);
    if (this["on" + (event.replace("on", ""))] == undefined) {
        this["on" + (event.replace("on", ""))] = function (e) {
            for (i in this.events["on" + (event.replace("on", ""))]) {
                this.events["on" + (event.replace("on", ""))][i](e);
            }
        }
    }
}

您将以这种方式使用它:

document.body.addEvent("click",function(){
   alert("Test");
});
document.body.addEvent("click",function(){
   alert("Test 2");
});
document.getElemntById("inputtest").addEvent("keyup",function(){
   alert("Input keyup");
});

答案 4 :(得分:-2)

请试一试。

function addEvent(elem,event,func)
{
    var evn = "on"+event;
    elem[evn] = func;
}
var obj = document.getElementById("link");
addEvent(obj,"click",function(){alert('hi');});

使用此代码,您无需担心attachEvent或addEventListener。此代码适用于所有浏览器。希望这能解决你的问题。