我必须提交。 一个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>
和其他一个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') ; }
我的脚本在Firefox,Safari,IE,Chrome上运行良好。 但是没有在Opera&amp;一些Android浏览器。 我的剧本有什么问题?
有人能解决这个问题吗?
答案 0 :(得分:2)
在脚本标记中添加defer='defer'
确实应该等到页面完全加载,但就像现在一样,即使这些天并非所有浏览器都支持它,即它们会忽略它,导致元素不存在代码执行时。
可以看到here的完整浏览器支持列表。快照:
你可能有旧版本的Opera或Opera mini,因此无效。
要解决此问题,请使用适用于所有浏览器的基本window.onload
来安全地使用它:
window.onload = function() {
byid('A1').onkeydown=function a1(){ alert('On Keydown'); }
byid('A2').onkeypress=function a2(){ alert('On Keypress') ; }
//...
};
替代方法是将脚本标记与JS文件的引用一起放在文档的最末端,就在</body>
标记之前 - 有或没有defer
。