2013-10-13 101 views
0

我必須提交文件。 一個HTML:如何通過JavaScript檢測事件?

<!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> 

與其他一個JavaScript的:

function byid(id_name) 
{ 
    return document.getElementById(id_name); 
} 

byid('A1').onkeydown=function a1(){ alert('On Keydown'); } 
byid('A2').onkeypress=function a2(){ alert('On Keypress') ; } 
byid('A3').onkeyup=function a3(){ alert('On Keyup') ; } 
byid('A4').onfocus=function a4(){ alert('On Focus'); } 
byid('A5').onblur=function a5(){ alert('On Blur') ; } 
byid('A6').onclick=function a6(){ alert('On Click') ; } 
byid('A7').onmousemove=function a7(){ alert('On Mouse Move') ; } 
byid('A8').onmouseover=function a8(){ alert('On Mouse Over') ; } 
byid('A9').onmouseout=function a9(){ alert('On Mouse Out') ; } 

我的腳本工作極大的火狐,Safari,IE,Chrome瀏覽器。 但沒有在Opera上工作&某些Android瀏覽器。 我的腳本有什麼問題?

任何人都可以解決這個問題嗎?

+0

你在Opera中檢查過控制檯嗎? –

+2

把它包裝在'window.onload = function(){...};' –

+0

@ShadowWizard:提問者會認爲'defer'會阻止這個必要 - 解釋爲什麼這是必要的。 –

回答

2

defer='defer'添加到腳本標記應該等到頁面完全加載後,但就目前而言,即使在目前,並非所有瀏覽器都支持它,即它們將忽略它,導致代碼在代碼不存在時被執行。

瀏覽器支持的完整列表可以看到here。快照:

你可能有舊版本的Opera和Opera迷你的,因此它沒有工作。

爲了解決這個只是發揮它的安全使用非常基本的window.onload這在所有瀏覽器的工作原理:

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

替代的方法是將腳本標籤放置在最末尾引用您的JS文件在</body>標記之前 - 有或沒有defer

相關問題