2015-12-26 34 views
0

我正在製作一個簡單列表,並且每次用戶輸入在窗體中寫入內容時,都會將其添加到無序列表中。但是一旦頁面重新加載,li就會消失。我已經閱讀了關於本地存儲的一些信息來解決這個問題,但我不知道如何使用它,或者即使這是正確的解決方案。我不知道它是否會有所幫助,但這裏是我的代碼。如何在重新加載後將更改保存到列表中

<!DOCTYPE html> 
<html> 
<head> 
<title>Page Title</title> 
<link rel="stylesheet" type="text/css" href="style.css"> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> 
<script src="script.js"></script> 
<script src="http://use.edgefonts.net/lato:n9,i4,n1,i7,i9,n7,i1,i3,n4,n3:all.js"></script> 
</head> 
<body> 
<form> 
<input type = 'text' name = 'to do' value = 'Write Here' class= 'input'> 

</input> 
</form> 
<button type='button' class= "d">Enter</button> 
<ul></ul> 
</body> 
</html> 

body{ 
background-color: #eae4dd 
} 

form { 
position: relative; 
width: 20em; 
height: auto 
} 

.input { 
width: 20em; 
margin: auto; 
position: absolute; 
font-size: 1.5em 
} 

button { 
position: relative; 
cursor: pointer; 
left: 24em; 
top: .05em; 
font-size: 1.3em; 
background-color: #ceecfc; 
border-color: #bff0f2; 
color: #0a1417 
} 

ul { 
list-style-type: none; 
} 

li { 

margin-top: .2em; 
font-size: 2em; 
margin-left: -1.3em; 
padding-left: .5em; 
background-color: rgb(95, 147, 170); 
font-family: lato; 
color: #baecf2; 
border-radius: .5em 
} 

$(document).ready(function(){ 
$("button").click(function(){ 
    var input = $('input').val(); 
    $("ul").append("<li>" + input + "</li>"); 
}); 
}); 
+0

見https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage – guest271314

回答

1

是的,你可以使用localStorage很容易地爲這個!讓您的JavaScript看起來像這樣

//This will set the list HTML if it exists in localstorage 
if (localStorage.listHTML) { 
    $("ul").html(localStorage.listHTML); 
} 

$("button").click(function() { 
    var input = $('input').val(); 
    $("ul").append("<li>" + input + "</li>"); 
    //This will update the value that is in localStorage when you add a new item 
    localStorage.listHTML = $("ul").html(); 
}); 

你甚至可以添加一個按鈕上點擊localStorage復位。

$("#reset").click(function() { 
    $("ul").html(""); 
    localStorage.listHTML = ""; 
}); 

Full example on JSFiddle

More info on localStorage

相關問題