jQuery 函数用于一些对象,比方说 window 对象。例如,我们通常会像下面这样把函数分配给加载事件:
window.onload = function() { // do this stuff when the page is done loading };
使用 jQuery 编写的功能相同的代码:
$(window).load(function() { // run this when the whole page has been downloaded });
您可能有所体会,等待窗口加载的过程是非常缓慢而且令人痛苦的,这是因为必须等整个页面加载完所有的内容,包括页面上所有的的图片。有的时候,您希望首先完成图片加载,但是在大多数情况下,您只需加载超文本标志语言(Hypertext Markup Language,HTML)就可以了。
通过在文档中创建特殊的 ready 事件,jQuery 解决了这个问题,方法如下: $(document).ready(function() { // do this stuff when the HTML is all ready });
使用快捷方式调用这个函数。这很简单,只需向 $() 函数传递一个函数就可以了: $(function() { // run this when the HTML is done downloading
});
<html>
<head>
<title>标题</title>
<script type="text/javascript" src="jQuery\jquery-1.11.1.min.js"></script>
<script type="text/javascript">
$(function(){
$('#external_links a').click(
function()
{
return confirm('You are going to visit: ' + this.href);
}
);
});
</script>
</head>
<body>
<div id="external_links">
<a href="http://www.baidu.com">baidu</a><br>
<a href="www.google.com">google</a><br>
</div>
<hr><hr>
</body>
</html>