标签:
对元素的操作和事件的绑定需要等待一个合适的时机,可以看下面的例子:
<!DOCTYPE html>
<meta charset="utf-8">
<html>
<head>
<title>1-1</title>
<script type="text/javascript">
document.getElementById("panel").onclick = function () {
alert("元素已经加载完毕 !");
}
/*执行错误*/
</script>
</head>
<body>
<div id="panel">click me.</div>
</body>
</html>
如果这样,还没有等待元素加载完就绑定事件,
<!DOCTYPE html>
<meta charset="utf-8">
<html>
<head>
<title>1-2</title>
</head>
<body>
<div id="panel">click me.</div>
<script type="text/javascript">
document.getElementById("panel").onclick = function () {
alert("元素已经加载完毕 !");
}
/*正确执行*/
</script>
</body>
</html>
第二种是放在window.onload中进行事件绑定:
<!DOCTYPE html>
<meta charset="utf-8">
<html>
<head>
<title>1-3</title>
<script type="text/javascript">
window.onload = function () {
document.getElementById("panel").onclick = function () {
alert("元素已经加载完毕 !");
}
}
</script>
</head>
<body>
<div id="panel">click me.</div>
</body>
</html>
第三种是jQuery的ready()方法传入绑定事件的方法:
<!DOCTYPE html>
<meta charset="utf-8">
<html>
<head>
<title>Panel</title>
<script src="jquery-1.11.2.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
document.getElementById("panel").onclick = function () {
alert("元素已经加载完毕 !");
}
})
</script>
</head>
<body>
<div id="panel">click me.</div>
</body>
</html>
根据ready()方法的API说明http://api.jquery.com/ready/。
这个方法接收一个function类型的参数ready(handler), 方法的作用是: Specify a function to execute when the DOM is fully loaded.
$( document ).ready( handler ) $().ready( handler ) (this is not recommended) $( handler )
<body onload="inlineBodyOnloadTimeCounter();">
The .ready() method is generally incompatible with the attribute. If load must be used, either do not use .ready() or use jQuery‘s .load() method to attach load event handlers to the window or to more specific items, like images.
说明ready()方法和<body onload=“”>是不兼容的.
注:文章来源于转载。
jQuery $(document).ready()和JavaScript onload事件
标签:
原文地址:http://www.cnblogs.com/moqiutao/p/4775841.html