我遇到localStorage
的问题,并且我尝试将其存储为值,如果文本框中没有localStorage
值,则应该说First Try
。这是代码:
JavaScript的:
// 1. onload - Fill the textbox named "myData" with data from local storage variable called
// 'myData'. If no local storage is available, fill the textbox with the words "First Try". If there is a value then, keep it. So, when the page refreshes it will still be there in the textbox.
function loadIt() {
var myData = document.getElementById("myData");
// place content from previous edit
if (!myData.value)
{
myData.value = window.localStorage.getItem('value');
}
// your content will be saved locally
window.localStorage.setItem('value', myData.value);
HTML:
<input type="text" id="myData" value=""/>
答案 0 :(得分:3)
在onload
事件中,您应该阅读本地存储并在文本框中设置存储的值,否则将其设为“首次尝试”。
window.onload = function(){
var val = localStorage.getItem('value'); // or localStorage.value
if(val == null)
val = "First try";
document.getElementById("myData").value = val;
}
在onbeforeunload
事件中,您应该检索文本框的值并将其保存在本地存储中。
window.onbeforeunload = function(){
localStorage.setItem('value', document.getElementById("myData").value); // or localStorage.value = document.getElementById("myData").value
}