了解 HTML 锚标记
让我们从以下示例开始:
在同一目录中创建三个页面: 测试.html index.html
您的 test.html:
<html>
<head>
<script>
function test()
{
alert('Going to google.com?');
window.location="http://google.com";
}
</script>
</head>
<body>
<a href='' onclick="test();">google.com</a><br/>
<input type="button" value="google" onclick="test();" />
<a href='' onmouseover="test();">google.com</a><br/>
</body>
</html>
现在在 IE 以及 firefox 或 crome 上检查 test.html 页面。
您会注意到以下几点:
- 按钮工作正常。
- 第一个超链接在 IE 和其他浏览器中的工作方式不同。在 IE 中,它带我们回到 index.html 页面,而在 Firefox 中,它停留在同一页面上。
- 对于第一个超链接,window.location 失败。
- 您无法单击第二个超链接,因为鼠标悬停事件将首先触发,并且效果完美!
为什么?
我主要感兴趣的是第三点,因为它甚至给我们发出警报,window.location 失败。
Let'u start with following example:
Create three pages in same directory:
test.html
index.html
Your test.html:
<html>
<head>
<script>
function test()
{
alert('Going to google.com?');
window.location="http://google.com";
}
</script>
</head>
<body>
<a href='' onclick="test();">google.com</a><br/>
<input type="button" value="google" onclick="test();" />
<a href='' onmouseover="test();">google.com</a><br/>
</body>
</html>
Now check test.html page on IE as well as firefox or crome.
You will notice following points:
- Button works perfectly.
- First hyperlink works differently in IE and other browser. In IE, it brings us back to index.html page, while in firefox, it stays on same page.
- For first hyperlink, window.location fails.
- Second hyperlink you cannot click on that, as mouse over event will fire first, and it works perfectly!
Why?
My major interest is on 3rd point, as it even gives us alert, window.location fails.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
JavaScript 事件触发,设置
window.location
,然后触发链接的默认操作,浏览器转到“”,(IIRC)将其解析为当前 URI。这与单击一个链接,然后快速单击另一个链接所获得的效果相同。浏览器在收到转到第二个的指令之前没有时间转到第一个,因此转到第二个。如果您延迟函数的返回(通过将警报放在第二位),它将为第一个 URL 的请求提供足够的时间来访问该 URL,而不是第二个 URL。
您需要取消默认操作,当您使用内部事件属性时(不推荐,unobtrusive JavaScript< /a> 是前进的方向),通过返回 false 来完成。
The JavaScript event fires,
window.location
is set, then the default action of the link fires and the browser goes to '', which (IIRC) resolves as the current URI.This is the same effect you get if you click on a link, then quickly click on a different link. The browser doesn't have time to go to the first one before receiving the instruction to go to the second one, and it goes to the second one. If you delay the return of the function (by putting the alert second) it gives enough time for the request for the first URL to go through for that one to be visited instead of the second.
You would need to cancel the default action which, when you're using intrinsic event attributes (not recommended, unobtrusive JavaScript is the way forward), is done by returning false.
试试这个:
Try this: