A, HTML code execution sequence
Second, explain the execution order window.onload () event
window.onload () event action
- onload event is triggered only after the entire page loads
- When the code is executed to ensure that all of the DOM object has been loaded
See specific code
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script type="text/javascript">
// 获取id为btn的按钮
var btn=document.getElementById("btn");
//为按钮绑定一个单击响应函数
btn.onclick=function(){
alert("hello");
</script>
</head>
<body>
<button id="btn">点我一下</button>
</body>
</html>
This code function is to achieve the page, click the button pop "hello"
, however, run into
var btn = document.getElementById ( "btn" );
Bug occurs because the Button button has not been performed, that is not a button, you can not get the button object
The solution:
The code that implements functions put into window.onload () event , at this time, such as after all documents executed, will trigger window.onload () event
code show as below:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script type="text/javascript">
window.onload=function(){
// 获取id为btn的按钮
var btn=document.getElementById("btn");
//为按钮绑定一个单击响应函数
btn.onclick=function(){
alert("hello");
}
}
</script>
</head>
<body>
<button id="btn">点我一下</button>
</body>
</html>