javascript 更改哈希时重新加载页面
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18774763/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reload page when changing hash
提问by andyfurniss
Reload page when changing hash.
更改哈希时重新加载页面。
I have a simple one-page site with several 'pages' on it. These pages are in one wide container which scrolls when you choose one. I have added a hash to the URL so that you can locate to specific pages directly. This just sets the style.left attribute when it matches a hash in a switch statement.
我有一个简单的一页网站,上面有几个“页面”。这些页面位于一个宽容器中,当您选择其中一个时会滚动。我在 URL 中添加了一个哈希值,以便您可以直接定位到特定页面。这只是在匹配 switch 语句中的哈希时设置 style.left 属性。
The problem is that when I change the hash value in the URL. For example, changing it from Home.html#Web to Home.html#Photos. When doing this, the page doesn't reload so the Setup function I've created that check for the hash isn't called and the page just remains where it is.
问题是当我更改 URL 中的哈希值时。例如,将其从 Home.html#Web 更改为 Home.html#Photos。执行此操作时,页面不会重新加载,因此不会调用我创建的用于检查散列的 Setup 函数,并且页面会保持原样。
Any ideas for a way to force the page to reload? Or a better solution?
关于强制页面重新加载的方法的任何想法?或者更好的解决方案?
Thanks, Andy
谢谢,安迪
回答by bfavaretto
Don't reload the page. Instead, set up a onhashchange
event handler, and adjust the left value from there:
不要重新加载页面。相反,设置一个onhashchange
事件处理程序,并从那里调整左值:
window.onhashchange = function() {
// do stuff
}
Otherwise, why using hash links instead of regular links? In any case, if you reallywant to reload, just put window.location.reload()
inside the onhashchange
handler...
否则,为什么使用哈希链接而不是常规链接?在任何情况下,如果你真的想重装,只是把window.location.reload()
里面onhashchange
的处理程序...
回答by Kailash Chandra Panigrahi
I had a JQuery function that fired on $('body').on('click', '.subcategory-link', function () { }); which detected if there was a hash appended to the URL in my case, so I kept that function the same and then just used a force reload whenever a hash change was detected: below i write the code pls try this one it wrok from me charm.
我有一个 JQuery 函数触发 $('body').on('click', '.subcategory-link', function () { }); 它检测到在我的情况下是否有附加到 URL 的哈希值,所以我保持该函数相同,然后在检测到哈希值更改时使用强制重新加载:下面我写了代码请试试这个它从我魅力.
$(document).ready(function() {
$('body').on('click', '.subcategory-link', function () { var data = $(this).attr('href');
alert($(this).attr('href'));
window.location.reload();
});
});
});