javascript 添加事件侦听器跨浏览器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10149963/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 08:50:36  来源:igfitidea点击:

adding event listener cross browser

javascriptevents

提问by Mohamed Mahmoud Zaki

my problem here:why doesn't this code work ????? ... the message doesn't appear

我的问题在这里:为什么这段代码不起作用????...消息没有出现

i'm trying to add event listener to element x on event click

我正在尝试在事件单击时将事件侦听器添加到元素 x

    function test()
    {
    alert("test");
    }

var EventsCrossBrowsers = 
 {
    addEvents:(function(element,event,func)
              {
                    if(element.addEventListener)
                    {
                        return elemenet.addEventListener(event,func,false);
                    }
                    else if(elemenet.attachEvent)
                    {
                        return elemenet.attachEvent("on"+event,func);
                    }
              }());
 }

 var x =document.getElementById("test");

EventsCrossBrowsers.addEvents(x,"click",test);

thanks alot jfriend00.... the most smiple way i think :-

非常感谢 jfriend00 .... 我认为最简单的方式:-

function test()
{
    alert("test");
}

function addEventsCrossBrowsers(elemenet,event,func)
{
    if(elemenet.addEventListener)
    {
        elemenet.addEventListener(event,func,false);
    }
    else if(elemenet.attachEvent)
    {
        elemenet.attachEvent("on"+event,func);
    }
}
var x =document.getElementById("test");
addEventsCrossBrowsers(x,"click",test);

your second way is almost the same except i don't understand the return ... thank you again...

您的第二种方式几乎相同,只是我不明白返回...再次感谢...

回答by jfriend00

In your function, I see you are using both elemenetand elementwhere they should be the same spelling. That would be at least part of the problem.

在您的函数中,我看到您同时使用了两者elemenetelement并且它们的拼写应该相同。那至少是问题的一部分。

I also see that your addEventsfunction is a self executing function which doesn't make sense in this regard. It seems like it should just be a normal function.

我还看到您的addEvents函数是一个自执行函数,在这方面没有意义。看起来它应该只是一个正常的功能。

Here's my cross browser event function. In addition to make one function for adding event handlers, it also normalizes the thispointer and the eventsobject so they can be treated the same in any browser too.

这是我的跨浏览器事件功能。除了创建一个用于添加事件处理程序的函数外,它还规范了this指针和events对象,以便它们在任何浏览器中也可以被相同地对待。

// add event cross browser
function addEvent(elem, event, fn) {
    // avoid memory overhead of new anonymous functions for every event handler that's installed
    // by using local functions
    function listenHandler(e) {
        var ret = fn.apply(this, arguments);
        if (ret === false) {
            e.stopPropagation();
            e.preventDefault();
        }
        return(ret);
    }

    function attachHandler() {
        // set the this pointer same as addEventListener when fn is called
        // and make sure the event is passed to the fn also so that works the same too
        var ret = fn.call(elem, window.event);   
        if (ret === false) {
            window.event.returnValue = false;
            window.event.cancelBubble = true;
        }
        return(ret);
    }

    if (elem.addEventListener) {
        elem.addEventListener(event, listenHandler, false);
        return {elem: elem, handler: listenHandler, event: event};
    } else {
        elem.attachEvent("on" + event, attachHandler);
        return {elem: elem, handler: attachHandler, event: event};
    }
}

function removeEvent(token) {
    if (token.elem.removeEventListener) {
        token.elem.removeEventListener(token.event, token.handler);
    } else {
        token.elem.detachEvent("on" + token.event, token.handler);
    }
}

If you want a simpler version without the propagation and default prevention options but with thisand eventnormalization, that would be this:

如果你想不传播和预防的默认选择,但有一个简单的版本thisevent正常化,这将是这样的:

// add event cross browser
function addEvent(elem, event, fn) {
    if (elem.addEventListener) {
        elem.addEventListener(event, fn, false);
    } else {
        elem.attachEvent("on" + event, function() {
            // set the this pointer same as addEventListener when fn is called
            return(fn.call(elem, window.event));   
        });
    }
}