使用不同的 Fragment ID 加载同一页面不会导致页面重新加载?
基本上,我在页面上有许多链接 - index.html,它们看起来像这样:
<li><a href="index.html#0">test 0</a></li>
<li><a href="index.html#1">test 1</a></li>
<li><a href="index.html#2">test 2</a></li>
<li><a href="index.html#3">test 3</a></li>
我在 window.onload 事件中附加了一个函数,它将打开一个包含片段 ID 的警报框,所以如果我单击第一个链接,我应该会收到一个带有“0”等的警报框。
但是,只有当我从 URL 栏访问 index.html 并按 Enter 键时,我才会收到警报框。当我点击链接时,没有出现警告框。我认为这是因为 window.onload 事件没有被调用...有谁知道如何解决这个问题?
Basically, I have a number of links on the page - index.html, they look something like this:
<li><a href="index.html#0">test 0</a></li>
<li><a href="index.html#1">test 1</a></li>
<li><a href="index.html#2">test 2</a></li>
<li><a href="index.html#3">test 3</a></li>
I attached a function in window.onload event that will open up an alert box containing the fragment ID, so if I click on the first link, I should get an alert box with "0", etc.
However, I only get an alert box when I access index.html from the URL bar and press enter. When I click on the links, no alert box showed up. I think it's because the window.onload event doesn't get called... Does anyone know how to solve this problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要
window.onhashchange
事件,该事件在锚点导航时触发https://developer.mozilla.org/en/DOM/window.onhashchange
对于不支持的 UA,您必须处理
document.links
上的 onclick 事件,并确定链接是否指向当前文档(即:只有 link.hash 与 location.href 不同)You need
window.onhashchange
event, which gets triggered on anchor navigationhttps://developer.mozilla.org/en/DOM/window.onhashchange
For unsupporting UAs you have to process onclick event on
document.links
and figure out if the link points to currect document (ie: only link.hash differs from location.href)更改片段的目的是在特定页面内从一个部分移动到另一个部分。当您单击其中一个链接时,它只会更改片段,页面本身保持不变。由于页面没有更改,因此没有页面加载事件,因此不会调用
onload
处理程序。您需要一个
onhashchange
处理程序而不是onload
处理程序。但请注意,并非所有浏览器都支持onhashchange
,因此您必须为某些浏览器使用手动版本。如果您经常做此类事情,那么您可能需要查看 Sammy 或类似的库来获取为您照顾细节。Changing the fragment is intended to move from section to section within a specific page. When you click one of your links it just changes the fragment, the page itself is left untouched. Since the page doesn't change, there is no page load event and thus the
onload
handler is not called.You need an
onhashchange
handler instead of anonload
handler. Beware though that not all browsers supportonhashchange
so you'll have to muck about with a hand rolled version for some browsers. If you're doing a lot of this sort of thing then you might want to look at Sammy or a similar library to take care of the details for you.