Hash 不适用于后退按钮;需要 javascript 来调用 url 更改函数
大家好,这段代码的目的是读取 url 中哈希值后面的内容,并根据该值显示特定的 div。现在它工作得很好,除了当你已经在网站上时尝试更改哈希值时(或者如果你点击后退按钮,这具有相同的效果:更改哈希值,但 div 未更改)。该网站的设计是为了确保每次 div 更改(页面的主要内容)时它都不会重新加载,因此我假设当您点击后退按钮或在哈希后输入不同的值时 div 不会更改的原因是因为页面已加载,并且 JavaScript 代码仅在页面加载时调用一次。我需要一种方法,以便在 url 更改时调用它。代码如下:
function hash() { var hash = window.location.hash.replace('#',''); 插入内容(哈希); }
Hey everyone, this code is meant to read what comes after the hash in the url and display a specific div depending on that value. Right now it works fine, except for when you try changing the hash while you're already on the site (or if you hit the back button, which has the same effect: changes the hash, but the div isnt changed). The site is made so that it doesnt reload with every div change (the main content of the page), so I'm assuming the reason the div doesnt change when you hit the back button or type in a different value after the hash is because the page is already loaded, and the javascript code is only called once on page load. I need a way for it to be called whenever the url is changed. Here's the code:
function hash() {
var hash = window.location.hash.replace('#','');
InsertContent(hash);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
恐怕这不是一个错误,而是一个功能。例如,Opera 将页面的确切状态存储在内存中。因此,如果您点击后退按钮,该状态将完全恢复。就像您从未更改过页面一样。
不过,更改哈希值应该可以通过在更改哈希值后立即调用
InsertContent()
来实现。这不起作用吗?你能给我们看一下代码吗?I'm afraid it's not a bug, it's a feature. Opera for example stores the exact state of a page in memory. So if you hit the back button, that state will be restored exactly. It's like you've never change the page.
Changing the hash should work though, by calling
InsertContent()
right after you've changed the hash. Doesn't that work? Can you show us the code?您需要轮询 window.location.hash 并查看它是否发生变化。某些浏览器支持 onhashchange 事件。
另一个讨论:On - window.location.hash - Change?
You need to poll the window.location.hash and see if it changes. Some browsers support onhashchange event.
Another discussion: On - window.location.hash - Change?
jQuery 有一个名为“address”的插件来解决这个问题
jQuery has a plugin called "address" to address this problem