【发布时间】:2010-07-11 02:40:40
【问题描述】:
假设我们在$(document).ready 回调中将.click() 处理程序附加到锚点(<a>) 标记。此处理程序将取消默认操作(遵循href)并显示警报。
我想知道回调将在什么时候执行,用户是否可以点击锚点(文档已显示在浏览器中)但尚未附加事件。
以下是包含锚点的不同 HTML 页面,但包含脚本的顺序不同。它们之间有什么区别(如果有的话)?不同的浏览器会有不同的表现吗?
第1页:
<html>
<head>
<title>Test 1</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$('a').click(function() {
alert('overriding the default action');
return false;
});
});
</script>
</head>
<body>
<a href="http://www.google.com">Test</a>
</body>
</html>
第2页:
<html>
<head>
<title>Test 1</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
</head>
<body>
<a href="http://www.google.com">Test</a>
<script type="text/javascript">
$(function() {
$('a').click(function() {
alert('overriding the default action');
return false;
});
});
</script>
</body>
</html>
第3页:
<html>
<head>
<title>Test 1</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<a href="http://www.google.com">Test</a>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$('a').click(function() {
alert('overriding the default action');
return false;
});
});
</script>
</body>
</html>
那么用户是否有可能通过单击锚点被重定向到href 并且永远不会看到警报(当然忽略禁用 javascript 的情况)?在我提供的任何示例中都会发生这种情况吗?
我只需要确保click 事件处理程序已附加到锚点,然后用户才有可能单击此锚点。我知道我可以提供一个空的href,然后在 javascript 中逐步增强它,但这是一个更普遍的问题。
如果 HTML 由 web 服务器快速生成,但 jquery 库需要时间从远程服务器获取,会发生什么情况?这会影响我的情况吗?与加载 DOM 相比,包含脚本的顺序是什么?它们可以并行完成吗?
【问题讨论】:
标签: javascript jquery