2014-04-17 7 views
0

localStorage에 문제가있어서 값을 저장하려고 시도하고 있습니다. localStorage 값이 없으면 First Try이됩니다.localStorage에 텍스트 상자 값을 올바르게 저장하는 방법은 무엇입니까?

자바 스크립트 :

// 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 : 로컬 스토리지를 읽고 텍스트 상자에서 설정해야 onload 이벤트에서

<input type="text" id="myData" value=""/> 

답변

3

가 값이 여기에 코드는 그렇지 않으면 "처음 시도"하십시오.

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 
} 
관련 문제