从现在开始进入JQuery的事件和应用了!
好了,言归正传!
ready()类似于onload().
但ready()只要页面的DOM结构(文档结构)加载后便触发!不包括图片等非文字媒体文件.
onload()需要页面的全部元素加载完后才触发!
ready()的使用方式有以下几种.
法一:
<span style="font-family:Times New Roman;font-size:12px;">$(document).ready(function(){do something})</span>
法二:
<span style="font-family:Times New Roman;font-size:12px;">$.ready(function(){do something})</span>
法三:
<span style="font-family:Times New Roman;font-size:12px;">$(function(){do something})</span>
例子.
<span style="font-family:Times New Roman;font-size:12px;"><body>
<h3>页面载入时触发ready()事件</h3>
<div id="tip"></div>
<input id="btntest" type="button" value="点下我" />
<script type="text/javascript">
$(document).ready(function(){
$("#btntest").bind("click", function () {
$("#tip").html("我被点击了!");
});
});
</script>
</body></span>
ready()和onload事件的利弊.
1、加载多个函数.
<span style="font-family:Times New Roman;font-size:12px;"><body onload="a();b()">
</body></span>
2、执行的顺序影响代码的运行效率.
如果有很多图片和flash文件,用onload()则需要等待很长时间,用ready()只需要等dom结构加载完即可触发.
对于图片放大缩小等应用,需要等页面所有加载完所有元素才能执行,所以可以使用$(window).load()方法.
<span style="font-family:Times New Roman;font-size:12px;"><script type="text/javascript">
$(window).load(function() {
alert("你好");
});
$(window).load(function() {
alert("再见");
});
</script></span>
上面的代码会顺序执行.
3、unload方法:在页面关闭时触发.
<span style="font-family:Times New Roman;font-size:12px;">$(window).unload(function() {
alert("good bye");
});</span>
4、dom加载前触发.
<span style="font-family:Times New Roman;font-size:12px;"><body>
<script type="text/javascript">
(function() {
alert("hello");
})(jQuery)
</script>
</body></span>
5、需要注意的一个问题。
<span style="font-family:Times New Roman;font-size:12px;"><body>
<div id="test">this is the content</div>
<script type="text/javascript">
alert($("#test").html());//正确,可以显示
</script>
</body></span>
<span style="font-family:Times New Roman;font-size:12px;"><body>
<script type="text/javascript">
alert($("#test").html());//错误,不能显示
</script>
<div id="test">this is the content</div>
</body></span>