Javascript会更改为丢失的dom

Javascript会更改为丢失的dom

本文介绍了当按下后退按钮时,Javascript会更改为丢失的dom的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

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

I have this view that changes the text inside a div.

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

The user can then click on a link to jump to another page. But when the user presses the "back" button all DOM changes are lost.

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

FF remembers the changed div text but Chrome and IE do not.

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

I've found similar question, but in my case it is not possible to summarize the state by a url hash because the div contains random data.

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

I need is so that when the user goes back, the div is filled from the identical series of numbers.

<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填充内容:

You can store your html in LocalStorage, so when user go back, you fill the content with your 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>

这篇关于当按下后退按钮时,Javascript会更改为丢失的dom的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 18:58