Save content of div with local storage, and displa

2019-02-20 22:54发布

问题:

I am trying to grab the contents of a <div> on a page on page load, and save it to localstorage.

When someone visits the homepage again, I would like the contents of this div to be displayed.

Whilst I can get functions to work with the use of form input fields and a submit, I cannot find a way to get this working using just contents and page load.

Any help appreciated!

Many thanks

回答1:

Without seeing your markup and code it's hard to know what might be the problem, you should be able to do something like the following

On the first page:

$(function() {
  localStorage["myKey"] = JSON.stringify($("#divWithContents").html());
});

On the page you want the contents displayed:

$(function() {
   if (localStorage["myKey"] != null) {
      var contentsOfOldDiv = JSON.parse(localStorage["myKey"]);    
      $("divWhereIwantStuffDisplayed").html(contentsOfOldDiv);
     } 
});