JavaScript addEvent 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8198449/
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
JavaScript addEvent function
提问by Yalmaz Khalil
I have an addEvent
function:
我有一个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>
and I'm trying to add the following to window.onload
:
我正在尝试将以下内容添加到window.onload
:
addEvent(window, 'load', function (){
// add another event
var link= document.getElementById('link');
addEvent(link, 'click', function () {alert('Hi'); });
});
My question is: why does the link
event not work?
我的问题是:为什么该link
事件不起作用?
回答by SLaks
You misspelled function
.
你拼错了function
。
回答by Hristo
Try this:
尝试这个:
function attachEvent(element, event, callbackFunction) {
if (element.addEventListener) {
element.addEventListener(event, callbackFunction, false);
} else if (element.attachEvent) {
element.attachEvent('on' + event, callbackFunction);
}
};
回答by island205
typeof (window.event) != 'undefined'
doesn't work really on chrome when I tested your code! this would be work fine:
当我测试你的代码时,它在 chrome 上真的不起作用!这将工作正常:
!!window.attachEvent
and i consider that using brace in if..esle
is a good practice.
我认为使用大括号if..esle
是一个很好的做法。
function addEvent(elem, event, func ) {
if (!!window.attachEvent){
elem.attachEvent('on' + event, func);
}
else{
elem.addEventListener(event, func, false);
}
}
回答by Guilherme Ferreira
Instead of working this way, try this:
与其这样工作,不如试试这个:
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);
}
}
}
}
You will use it this way:
您将这样使用它:
document.body.addEvent("click",function(){
alert("Test");
});
document.body.addEvent("click",function(){
alert("Test 2");
});
document.getElemntById("inputtest").addEvent("keyup",function(){
alert("Input keyup");
});
回答by AmGates
Please try this.
请试试这个。
function addEvent(elem,event,func)
{
var evn = "on"+event;
elem[evn] = func;
}
var obj = document.getElementById("link");
addEvent(obj,"click",function(){alert('hi');});
Here using this code you need not worry about attachEvent or addEventListener. This code will work for all browser. Hope this solves your problem.
在这里使用此代码您无需担心 attachEvent 或 addEventListener。此代码适用于所有浏览器。希望这能解决您的问题。