2010-08-26 36 views
2

我想知道为什么this page的源使用所有的if-else添加一个事件侦听器:试图了解JavaScript的关键事件处理

if (document.addEventListener) 
{ 
    document.addEventListener("keydown",keydown,false); 
    document.addEventListener("keypress",keypress,false); 
    document.addEventListener("keyup",keyup,false); 
    document.addEventListener("textInput",textinput,false); 
} 
else if (document.attachEvent) 
{ 
    document.attachEvent("onkeydown", keydown); 
    document.attachEvent("onkeypress", keypress); 
    document.attachEvent("onkeyup", keyup); 
    document.attachEvent("ontextInput", textinput); 
} 
else 
{ 
    document.onkeydown= keydown; 
    document.onkeypress= keypress; 
    document.onkeyup= keyup; 
    document.ontextinput= textinput; // probably doesn't work 
} 

是它与大多数的浏览器兼容?

回答

1
if (document.addEventListener) // DOM spec that all browsers should follow 

else if (document.attachEvent) // but unfortunately IE does not follow them  

else // and there may be other older browsers that follow neither 
+0

此评论与您的​​照片完全一致.. XD谢谢! – 2010-08-26 18:52:42

+0

谢谢,我认为这是一种恭维:D < - btw,这与我的个人资料图片最为一致 – Anurag 2010-08-26 18:59:04