我正在为我的应用程序使用 JavaScript 模板,类似于此:
<script id="my-template" type="text/template">
<!-- Template here -->
</script>
根据用户执行的操作将每个此类模板的内容加载到 #container
div 中。
问题是这一切都发生在同一页面上,因此当用户单击浏览器中的后退和前进按钮时,他们将转到他们所在的上一个网页,而不是我的应用程序中的相关屏幕。有没有办法说如果我在加载模板时将 #my-template-id
字符串添加到我的 url,或者知道要转到哪个页面/要加载哪个模板?
最佳答案
是的,只需将 window.location.hash
设置为您要添加的哈希值(不包括 #)。要查看当前哈希是什么,只需使用 window.location.hash
字符串(参见下面的示例)。如果您想根据散列更改 View ,也可以监听散列更改。为此,请使用 onhashchange
监听器。请注意,当您通过 window.location.hash
更改散列时,它会触发 onhashchange。使用标志可以避免混淆,例如
//making hash change
imChangingHash = true;
window.location.hash = 'thisPage';
$(window).on('hashchange',function(){
if(imChangingHash) {
imChangingHash = false;
return;
}
//this is now a back/forward button hash change
console.log('back - forward button moved page to: ' + window.location.hash);
});
关于javascript - 返回按钮从 javascript 模板加载相关的 html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29716657/