如何通过JavaScript检测事件?

如何通过JavaScript检测事件?,javascript,html,Javascript,Html,我必须归档。 一个HTML: <!DOCTYPE html> <html> <head> <meta http-equiv='Content-type' content='text/html; charset=utf-8'> <title>JavaScriptSolution</title> <script src='./script.js' charset='utf-8' defer='def

我必须归档。 一个HTML:

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv='Content-type' content='text/html; charset=utf-8'>
    <title>JavaScriptSolution</title>
    <script src='./script.js' charset='utf-8' defer='defer'></script>
</head>
<body>
<input id='A1' value='On Keydown' style='width:100px; height:50px; margin:30px;'/>

<input id='A2' value='On Keyress' style='width:100px; height:50px; margin:30px;'/>

<input id='A3' value='On Keyup' style='width:100px; height:50px; margin:30px;'/>

<input id='A4' value='On Focus' style='width:100px; height:50px; margin:30px;'/>

<input id='A5' value='On Blur' style='width:100px; height:50px; margin:30px;'/>

<div id='A6' style='width:100px; height:50px; margin:30px;'>
    On Click
</div>
<div id='A7' style='width:100px; height:50px; margin:30px;'>
    On Mouse Move
</div>
<div id='A8' style='width:100px; height:50px; margin:30px;'>
    On Mouse Over
</div>
<div id='A9' style='width:100px; height:50px; margin:30px;'>
    On Mouse Out
</div>


</body>
</html>
我的脚本在Firefox、Safari、IE、Chrome上运行得很好。 但在Opera和一些Android浏览器上无法工作。 我的剧本怎么了


有人能解决这个问题吗?

defer='defer'
添加到脚本标记中确实应该等到页面完全加载后,但是现在,即使是现在,也不是所有浏览器都支持它,即他们会忽略它,导致代码执行时元素不存在

可以看到浏览器支持的完整列表。快照:

您可能有旧版本的Opera或Opera mini,因此它不起作用

要解决这个问题,只需使用非常基本的
窗口。onload
即可在所有浏览器上运行:

window.onload = function() {
    byid('A1').onkeydown=function a1(){ alert('On Keydown'); }
    byid('A2').onkeypress=function a2(){ alert('On Keypress') ; }
    //...
};

另一种方法是将脚本标记和对JS文件的引用放在文档的最末尾,就在
标记之前-带或不带
defer

是否在Opera中检查了控制台?将其包装在
window.onload=function(){…}中
@ShadowWizard:提问者会认为,
延迟
会阻止这一点的必要性-解释一下为什么这是必要的是好的。Opera 16(最新版本)只是基于Chromium!不要为旧浏览器操心太多!为用户提供更新!我把它包在窗户里。没装。很好!
window.onload = function() {
    byid('A1').onkeydown=function a1(){ alert('On Keydown'); }
    byid('A2').onkeypress=function a2(){ alert('On Keypress') ; }
    //...
};