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

时间:2015-04-18 11:25:34

标签: javascript jquery html html5 templates

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

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

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

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

3 个答案:

答案 0 :(得分:0)

是的,只需使用您要添加的哈希设置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);
});

答案 1 :(得分:-1)

您可能需要查看history js

答案 2 :(得分:-1)

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

以下是fullstack框架中使用的两个示例: