如何使用HTML5的Web存储API保存和检索整个<div>

时间:2018-12-24 11:03:34

标签: javascript html local-storage web-storage

我想在从javascript中添加html之后保存并检索html的某些内容,并且在刷新后不丢失它们

// hide/show the header
$("#icon").click(function(){
	$("#add-new-todo").fadeToggle();
});


// delete a todo onclick
$("#todo").on("click", ".delete", function(event) {
	$(this).parent().fadeOut(500, function() {
		$(this).remove();
	});

	event.stopPropagation();
});


//function that scratch the finished todo
$("#todo").on("click", ".todoList", function() {
	$(this).toggleClass("completed");
});
		
// format date to: weekday - year - month - day - time
function formatDate()
{
	var event = new Date();
	var options = { weekday: 'long', year: 'numeric', month: 'long', 
					day: 'numeric', hour: 'numeric', minute: 'numeric'};

	return event.toLocaleDateString('en-US', options);
}


// clear the input field after adding a todo
function clearAll() {
	let title = document.getElementById('todoTitle');
	let content = document.getElementById('todoContent');

	title.value = "";
	content.value = "";
}


// add a new todo
function addNewToDo()
{
	let title = document.getElementById('todoTitle');
	let content = document.getElementById('todoContent');

	if ((title.value == null || title.value == "") ||
		(content.value == null || content.value == "")) {
		alert("Please fill all the required fields!");
		// clearAll();
		return false;
	}

	let parentDiv = document.getElementById('todo');

	let newDiv = document.createElement("div");
	newDiv.className = "todoList";

	let conDiv = document.createElement("div");
	conDiv.className = "content";

	let delDiv = document.createElement("div");
	delDiv.className = "delete";
	delDiv.innerHTML = "<i class='fas fa-times'></i>";

	let header = document.createElement("h2");
	header.innerHTML = title.value;

	let dateContent = document.createElement("p");
	dateContent.className = "date";
	let date = formatDate();
	dateContent.innerHTML = "added: " + date;

	let subject = document.createElement("p");
	subject.className = "subject";
	subject.innerHTML = content.value;

	conDiv.appendChild(header);
	conDiv.appendChild(dateContent);
	conDiv.appendChild(subject);
	
	newDiv.appendChild(delDiv);
	newDiv.appendChild(conDiv);
	// newDiv.appendChild(delDiv);

	parentDiv.appendChild(newDiv);

	clearAll();
}
body {
    background: #2BC0E4;  /* fallback for old browsers */
    background: -webkit-linear-gradient(to right, #EAECC6, #2BC0E4);  /* Chrome 10-25, Safari 5.1-6 */
    background: linear-gradient(to right, #EAECC6, #2BC0E4); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
}

#container {
    font-family: 'Roboto', sans-serif;
    width: 400px;
    margin: 150px auto;
    background: #f7f7f7;
    box-shadow: 0 0 3px rgba(0, 0, 0, 0.1);
    border-radius: 3%;
}

#todo {
    padding-bottom: 5px;
}

#title {
    background-color: #2980b9;
    color: white;
    margin: 0;
    text-transform: uppercase;
    font-size: 18px;
    text-align: center;
}

#items-title {
    margin: 10px auto;
    padding-left: 20px;
}

form {
    margin: 10px auto;
    padding-left: 20px;
}


.form-lines:first-child input {
    border-radius: 5%;
}

.form-lines:first-child input[type="text"] {
    width: 62%;
    height: 35px;
    padding-left: 20px;
    box-sizing: border-box;
    background-color: #f7f7f7;
    border: 2px solid rgba(0,0,0,0.2);
    word-wrap: break-word;
}

#todoButton {
    width: 28%;
    height: 30px;
    background-color: #2980b9;
    color: #fff;
    border: none;
}

#todoButton:hover {
    background-color: #206592;
    font-size: 19px;
}

.form-lines:nth-child(2) input {
    margin: 5px auto 0;
    width: 92%;
    height: 60px;
    border-radius: 5%;
    padding-left: 20px;
    box-sizing: border-box;
    word-wrap: break-word;
    background-color: #f7f7f7;
    border: 2px solid rgba(0,0,0,0.2);

}

.form-lines input[type="text"]:focus {
    border: 2px solid #2980b9;
    background-color: #fff;
}


#icon {
    float: right;
    padding-right: 20px; 
}

hr {
    width: 50%;
    margin: 0px auto 5px;
}

.todoList {
    width: 93%;
    border: 2px solid rgba(0,0,0,0.2);
    border-radius: 5%;
    margin: auto auto 5px;
    padding-left: 20px;
    box-sizing: border-box;
}

.delete {
    float: right;
    padding: 10px 15px;
    margin: 40px 10px 0px;
    background-color: red;
    color: white;
    font-size: 25px;
    border-radius: 10%;
}

.content h2 {
    margin: 10px 0;
    font-size: 30px;
    text-transform: capitalize;
    word-wrap: break-word;
}

.content .date {
    font-size: 13px;
    color: rgba(0,0,0,0.75);
    margin: 0;
    width: 77%;
    word-wrap: break-word;
}

.conten .subject {
    margin: 15px auto;
    font-size: 23px;
    color: black;
    padding-top: 10px;
    padding-right: 3px;
    word-wrap: break-word;
}

.completed {
    color: gray;
    text-decoration: line-through;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!doctype html>
<html class="no-js" lang="">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <title></title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="apple-touch-icon" href="apple-touch-icon.png">

        <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
        <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous">

        <link rel="stylesheet" href="css/normalize.min.css">
        <link rel="stylesheet" href="css/main.css">

        <script src="js/vendor/modernizr-2.8.3.min.js"></script>
    </head>
    <body>

    	<div id="container">
    		<div id="header">
    			<div id="title">
    				<div>
                        <h1>
                            SEF Todo List<span id="icon"><i class="fas fa-minus"></i></span>
                        </h1> 
           
                    </div>
    			</div>

    			<div id="add-new-todo">
    				<div id="items-title">
    					<h1>Item</h1>	
    				</div>

					<form>
						<div class="form-lines">					
							<input type="text" name="todoTitle" placeholder="Enter title" id="todoTitle">
							<input type="button" name="todoButton" value="Add" id="todoButton" onclick="addNewToDo()">
						</div>

						<div class="form-lines">
							<input type="text" name="todoContent" placeholder="Enter what To Do" id="todoContent">
						</div>

					</form>	
    			</div>
    		</div>
    		<hr>
    		<div id="todo"></div>
    	</div>




        <!--[if lt IE 8]>
            <p class="browserupgrade">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p>
        <![endif]-->

        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
        <script>window.jQuery || document.write('<script src="js/vendor/jquery-1.11.2.min.js"><\/script>')</script>

        <script src="js/plugins.js"></script>
        <script src="js/main.js"></script>

        <!-- Google Analytics: change UA-XXXXX-X to be your site's ID. -->
        <script>
            (function(b,o,i,l,e,r){b.GoogleAnalyticsObject=l;b[l]||(b[l]=
            function(){(b[l].q=b[l].q||[]).push(arguments)});b[l].l=+new Date;
            e=o.createElement(i);r=o.getElementsByTagName(i)[0];
            e.src='//www.google-analytics.com/analytics.js';
            r.parentNode.insertBefore(e,r)}(window,document,'script','ga'));
            ga('create','UA-XXXXX-X','auto');ga('send','pageview');
        </script>
    </body>
</html>

这是我所有文件的代码,该项目是关于构建一个小型的待办Web应用程序,该应用程序应使用浏览器的存储空间 我试图使用localStorage,但是它将div保存为没有内容的对象

新的divs使用javascript addNewToDo()插入 我想将所有附加的div存储在该div中,以便在重新加载页面时检索它们

提前感谢

更新: 在询问讲师更多细节后,他说我们不应该存储整个div标签,我们感兴趣的是它包含的内容

所以这是我的解决方案,请随时提供您的反馈,我将不胜感激

// initialize the itemsArray to [] or to the existing previous todos
let itemsArray = localStorage.getItem('items') ? JSON.parse(localStorage.getItem('items')) : [];
localStorage.setItem('items', JSON.stringify(itemsArray));
var data = JSON.parse(localStorage.getItem('items'));


// hide/show the header
$("#icon").click(function(){
	$("#add-new-todo").fadeToggle();
});


// delete a todo onclick
$("#todo").on("click", ".delete", function(event) {
	$(this).parent().fadeOut(500, function() {
		let idxDel = $(this).index();
		
		// call the function that deletes the div from the localStorage
		deleteFromStorage(idxDel);
		$(this).remove();
	});
	event.stopPropagation();
});


//function that scratch the finished todo
$("#todo").on("click", ".todoList", function() {
	$(this).toggleClass("completed");
});
		

// format date to: weekday - year - month - day - time
function formatDate()
{
	var event = new Date();
	var options = { weekday: 'long', year: 'numeric', month: 'long', 
					day: 'numeric', hour: 'numeric', minute: 'numeric', hour12: false};

	return event.toLocaleDateString('en-US', options);
}


// clear the input field after adding a todo
function clearAll() {
	let title = document.getElementById('todoTitle');
	let content = document.getElementById('todoContent');

	title.value = "";
	content.value = "";
}


// add a new todo
function addNewToDo()
{
	let title = document.getElementById('todoTitle');
	let content = document.getElementById('todoContent');

	if ((title.value == null || title.value == "") ||
		(content.value == null || content.value == "")) {
		alert("Please fill all the required fields!");
		return false;
	}

	let parentDiv = document.getElementById('todo');

	let newDiv = document.createElement("div");
	newDiv.className = "todoList";

	let conDiv = document.createElement("div");
	conDiv.className = "content";

	let delDiv = document.createElement("div");
	delDiv.className = "delete";
	delDiv.innerHTML = "<i class='fas fa-times'></i>";

	let header = document.createElement("h2");
	header.innerHTML = title.value;

	let dateContent = document.createElement("p");
	dateContent.className = "date";
	let date = formatDate();
	dateContent.innerHTML = "added: " + date;

	let subject = document.createElement("p");
	subject.className = "subject";
	subject.innerHTML = content.value;

	conDiv.appendChild(header);
	conDiv.appendChild(dateContent);
	conDiv.appendChild(subject);
	
	newDiv.appendChild(delDiv);
	newDiv.appendChild(conDiv);

	addToLocalStorage(title.value, "added: " + date, content.value);

	parentDiv.appendChild(newDiv);

	clearAll();
}


// save the added todo to the localStorage
function addToLocalStorage (title, date, subject)
{
	obj = {"title" : String(title),
		   "date": String(date),
		   "subject": String(subject)};
	itemsArray.push(obj);

	// add the new item added to data array to be available for other functions
	data = itemsArray;
	localStorage.setItem('items', JSON.stringify(itemsArray));
} 


// retrieve all the todos from the localStorage
function retrieveToDo()
{
	let parentDiv = document.getElementById('todo');
	
	for (let i = 0; i < data.length; i++) {

		let newDiv = document.createElement("div");
		newDiv.className = "todoList";

		let conDiv = document.createElement("div");
		conDiv.className = "content";

		let delDiv = document.createElement("div");
		delDiv.className = "delete";
		delDiv.innerHTML = "<i class='fas fa-times'></i>";

		let header = document.createElement("h2");
		header.innerHTML = data[i].title;

		let dateContent = document.createElement("p");
		dateContent.className = "date";
		dateContent.innerHTML = data[i].date;

		let subject = document.createElement("p");
		subject.className = "subject";
		subject.innerHTML = data[i].subject;

		conDiv.appendChild(header);
		conDiv.appendChild(dateContent);
		conDiv.appendChild(subject);
		
		newDiv.appendChild(delDiv);
		newDiv.appendChild(conDiv);

		parentDiv.appendChild(newDiv);
	}
}


// delete a specific todo from the localStorage
function deleteFromStorage(idxDel)
{
	data.splice(idxDel, 1);;
	localStorage.setItem('items', JSON.stringify(data));
}

1 个答案:

答案 0 :(得分:0)

我认为最好将json保存为地图;但是,如果要使用html,可以在附加newDIV之后保存todoList,如下所示:

        parentDiv.appendChild(newDiv);
        storage.setItem('originList', parentDiv.innerHTML);

在页面中,您应该初始化addNewToDo函数。像这样:

         if (type) {
            var originListHtml = storage.getItem('originList');
            if (!parentDiv.innerHTML) {
                parentDiv.innerHTML = originListHtml;
            }
            return;
        }

以上可以确定;请参见以下示例,希望可以为您提供帮助:)

// hide/show the header
$("#icon").click(function() {
  $("#add-new-todo").fadeToggle();
});


// delete a todo onclick
$("#todo").on("click", ".delete", function(event) {
  $(this).parent().fadeOut(500, function() {
    $(this).remove();
  });

  event.stopPropagation();
});


//function that scratch the finished todo
$("#todo").on("click", ".todoList", function() {
  $(this).toggleClass("completed");
});

// format date to: weekday - year - month - day - time
function formatDate() {
  var event = new Date();
  var options = {
    weekday: 'long',
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    hour: 'numeric',
    minute: 'numeric'
  };

  return event.toLocaleDateString('en-US', options);
}


// clear the input field after adding a todo
function clearAll() {
  let title = document.getElementById('todoTitle');
  let content = document.getElementById('todoContent');

  title.value = "";
  content.value = "";
}


// add a new todo
function addNewToDo(type) {
  let title = document.getElementById('todoTitle');
  let content = document.getElementById('todoContent');

  // 判断初始化的时候显示之前localStorage的内容
  if (type) {
    var originListHtml = storage.getItem('originList');
    if (!parentDiv.innerHTML) {
      parentDiv.innerHTML = originListHtml;
    }
    return;
  }
  if ((title.value == null || title.value == "") ||
    (content.value == null || content.value == "")) {
    alert("Please fill all the required fields!");
    // clearAll();
    return false;
  }

  let parentDiv = document.getElementById('todo');

  let newDiv = document.createElement("div");
  newDiv.className = "todoList";

  let conDiv = document.createElement("div");
  conDiv.className = "content";

  let delDiv = document.createElement("div");
  delDiv.className = "delete";
  delDiv.innerHTML = "<i class='fas fa-times'></i>";

  let header = document.createElement("h2");
  header.innerHTML = title.value;

  let dateContent = document.createElement("p");
  dateContent.className = "date";
  let date = formatDate();
  dateContent.innerHTML = "added: " + date;

  let subject = document.createElement("p");
  subject.className = "subject";
  subject.innerHTML = content.value;

  conDiv.appendChild(header);
  conDiv.appendChild(dateContent);
  conDiv.appendChild(subject);

  newDiv.appendChild(delDiv);
  newDiv.appendChild(conDiv);
  // newDiv.appendChild(delDiv);

  parentDiv.appendChild(newDiv);
  // 存储todoList
  storage.setItem('originList', parentDiv.innerHTML);

  clearAll();
}
//初始化todoList
addNewToDo('init');
body {
  background: #2BC0E4;
  /* fallback for old browsers */
  background: -webkit-linear-gradient(to right, #EAECC6, #2BC0E4);
  /* Chrome 10-25, Safari 5.1-6 */
  background: linear-gradient(to right, #EAECC6, #2BC0E4);
  /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
}

#container {
  font-family: 'Roboto', sans-serif;
  width: 400px;
  margin: 150px auto;
  background: #f7f7f7;
  box-shadow: 0 0 3px rgba(0, 0, 0, 0.1);
  border-radius: 3%;
}

#todo {
  padding-bottom: 5px;
}

#title {
  background-color: #2980b9;
  color: white;
  margin: 0;
  text-transform: uppercase;
  font-size: 18px;
  text-align: center;
}

#items-title {
  margin: 10px auto;
  padding-left: 20px;
}

form {
  margin: 10px auto;
  padding-left: 20px;
}

.form-lines:first-child input {
  border-radius: 5%;
}

.form-lines:first-child input[type="text"] {
  width: 62%;
  height: 35px;
  padding-left: 20px;
  box-sizing: border-box;
  background-color: #f7f7f7;
  border: 2px solid rgba(0, 0, 0, 0.2);
  word-wrap: break-word;
}

#todoButton {
  width: 28%;
  height: 30px;
  background-color: #2980b9;
  color: #fff;
  border: none;
}

#todoButton:hover {
  background-color: #206592;
  font-size: 19px;
}

.form-lines:nth-child(2) input {
  margin: 5px auto 0;
  width: 92%;
  height: 60px;
  border-radius: 5%;
  padding-left: 20px;
  box-sizing: border-box;
  word-wrap: break-word;
  background-color: #f7f7f7;
  border: 2px solid rgba(0, 0, 0, 0.2);
}

.form-lines input[type="text"]:focus {
  border: 2px solid #2980b9;
  background-color: #fff;
}

#icon {
  float: right;
  padding-right: 20px;
}

hr {
  width: 50%;
  margin: 0px auto 5px;
}

.todoList {
  width: 93%;
  border: 2px solid rgba(0, 0, 0, 0.2);
  border-radius: 5%;
  margin: auto auto 5px;
  padding-left: 20px;
  box-sizing: border-box;
}

.delete {
  float: right;
  padding: 10px 15px;
  margin: 40px 10px 0px;
  background-color: red;
  color: white;
  font-size: 25px;
  border-radius: 10%;
}

.content h2 {
  margin: 10px 0;
  font-size: 30px;
  text-transform: capitalize;
  word-wrap: break-word;
}

.content .date {
  font-size: 13px;
  color: rgba(0, 0, 0, 0.75);
  margin: 0;
  width: 77%;
  word-wrap: break-word;
}

.conten .subject {
  margin: 15px auto;
  font-size: 23px;
  color: black;
  padding-top: 10px;
  padding-right: 3px;
  word-wrap: break-word;
}

.completed {
  color: gray;
  text-decoration: line-through;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!doctype html>
<html class="no-js" lang="">

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <title></title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="apple-touch-icon" href="apple-touch-icon.png">

  <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous">

  <link rel="stylesheet" href="css/normalize.min.css">
  <link rel="stylesheet" href="css/main.css">

  <script src="js/vendor/modernizr-2.8.3.min.js"></script>
</head>

<body>

  <div id="container">
    <div id="header">
      <div id="title">
        <div>
          <h1>
            SEF Todo List<span id="icon"><i class="fas fa-minus"></i></span>
          </h1>

        </div>
      </div>

      <div id="add-new-todo">
        <div id="items-title">
          <h1>Item</h1>
        </div>

        <form>
          <div class="form-lines">
            <input type="text" name="todoTitle" placeholder="Enter title" id="todoTitle">
            <input type="button" name="todoButton" value="Add" id="todoButton" onclick="addNewToDo()">
          </div>

          <div class="form-lines">
            <input type="text" name="todoContent" placeholder="Enter what To Do" id="todoContent">
          </div>

        </form>
      </div>
    </div>
    <hr>
    <div id="todo"></div>
  </div>




  <!--[if lt IE 8]>
            <p class="browserupgrade">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p>
        <![endif]-->

  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
  <script>
    window.jQuery || document.write('<script src="js/vendor/jquery-1.11.2.min.js"><\/script>')
  </script>

  <script src="js/plugins.js"></script>
  <script src="js/main.js"></script>

  <!-- Google Analytics: change UA-XXXXX-X to be your site's ID. -->
  <script>
    (function(b, o, i, l, e, r) {
      b.GoogleAnalyticsObject = l;
      b[l] || (b[l] =
        function() {
          (b[l].q = b[l].q || []).push(arguments)
        });
      b[l].l = +new Date;
      e = o.createElement(i);
      r = o.getElementsByTagName(i)[0];
      e.src = '//www.google-analytics.com/analytics.js';
      r.parentNode.insertBefore(e, r)
    }(window, document, 'script', 'ga'));
    ga('create', 'UA-XXXXX-X', 'auto');
    ga('send', 'pageview');
  </script>
</body>

</html>