繁体   English   中英

返回按钮以从javascript模板加载相关的html

[英]Go back button to load related html from javascript template

我正在为我的应用程序使用JavaScript模板,类似于以下内容:

<script id="my-template" type="text/template">
    <!-- Template here -->
</script>

根据用户执行的操作将每个此类模板的内容加载到#container div中。

问题是这一切都发生在同一页面上,因此,当用户在浏览器中单击后退和前进按钮时,他们将转到他们所在的上一个网页,而不是我的应用程序中的相关屏幕。 有没有办法说在加载#my-template-id时是否在我的URL中添加#my-template-id字符串,或者是否知道要转到哪个页面/要加载哪个模板?

是的,只需将window.location.hash设置为您要添加的哈希(不包括#)。 要查看当前的哈希值是什么,只需使用window.location.hash字符串(请参见下面的示例)。 如果要基于哈希更改视图,也可以侦听哈希更改。 为此,请使用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);
});

您可能想看看历史记录js

是的,您需要在应用程序中使用某种路由器,它将为您处理片段。

这是全栈框架中使用的2个示例:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM