繁体   English   中英

当按下后退按钮时,Javascript会更改为丢失的dom

[英]Javascript changes to the dom lost when back button pressed

我有这个视图,改变div内的文本。

然后,用户可以单击链接以跳转到另一个页面。 但是当用户按下“后退”按钮时,所有DOM更改都将丢失。

FF会记住更改的div文本,但Chrome和IE不会。

我发现了类似的问题,但在我的情况下,不可能通过url哈希来概括状态,因为div包含随机数据。

我需要的是当用户返回时,div从相同的数字序列中填充。

<script type="text/javascript">
    function ChangeText() {
        var newText = "";

        for (var i = 0; i < 10; i++) {
            newText = newText + Math.random() * 100;
            newText = newText + "<br />";
        }

        $("#container").html(newText);
    }
</script>

<div id="container">
    INITIAL TEXT
</div>
<button onclick="ChangeText()">Click here to generate random numbers</button>
<br/>
<a href="http://www.google.com">External link</a>

您可以将您的html存储在LocalStorage中,因此当用户返回时,您可以使用localStorage填充内容:

<script type="text/javascript">
    function onLoadPage(){
        if(window.localStorage.getItem("newText") != null){
            $("#container").html(window.localStorage.getItem("newText"));
        }
    }

    function ChangeText() {
        var newText = "";

        for (var i = 0; i < 10; i++) {
            newText = newText + Math.random() * 100;
            newText = newText + "<br />";
        }

        window.localStorage.setItem("newText") = newText;

        $("#container").html(newText);
    }
</script>

<div id="container">
    INITIAL TEXT
</div>
<button onclick="ChangeText()">Click here to generate random numbers</button>
<br/>
<a href="http://www.google.com">External link</a>

暂无
暂无

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

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