最近在我的网站上,我观察到有时候我的代码在路由器重启或中断时会丢失。我想使用本地存储来存储我的textarea的值。我的代码主要由javascript组成,所有细节都是用html完成的。我不想干涉我现在的JavaScript。如果有人知道请提交您的JavaScript和textarea。
TA, 杰克
我的textarea代码如下;
<div class = "fixed">
<center>
<table>
<tr><td>Type here</td></tr>
<tr>
<td colspan="3">
<textarea id="inputTextToSave" style="width:512px;height:256px"></textarea>
</td>
</tr>
<tr>
<td>Save As:</td>
<td><input id="inputFileNameToSaveAs"></input></td>
<td><button onclick="saveTextAsFile()"><img src="fl.gif" Save</button></td>
</tr>
<tr>
<td>Select file Load:</td>
<td><input type="file" id="fileToLoad"></td>
<td><button onclick="loadFileAsText()">Load File</button><td>
</tr>
</table>
</center>
<hr>
<script type='text/javascript'>
function saveTextAsFile()
{
var textToWrite = '<html> <body> <link rel="stylesheet" type="text/css" href="ceedweb.css" /> <!--ceedweb, always changing-->';
textToWrite += document.getElementById("inputTextToSave").value;
textToWrite += '</body> </html>';
var textFileAsBlob = new Blob([textToWrite], {type:'text/html'});
var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value;
var downloadLink = document.createElement("a");
downloadLink.download = fileNameToSaveAs;
downloadLink.innerHTML = "Download File";
if (window.webkitURL != null)
{
downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
}
else
{
downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
downloadLink.onclick = destroyClickedElement;
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
}
downloadLink.click();
}
function destroyClickedElement(event)
{
document.body.removeChild(event.target);
}
function loadFileAsText()
{
var fileToLoad = document.getElementById("fileToLoad").files[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent)
{
var textFromFileLoaded = fileLoadedEvent.target.result;
document.getElementById("inputTextToSave").value = textFromFileLoaded;
};
fileReader.readAsText(fileToLoad, "UTF-8");
}
</script>
</div>
&#13;
答案 0 :(得分:0)
您可以将localstorage用作localstorage.setItem('some_key','some_value')
,然后将其检索为localstorage.getItem('some_key')
。
但要注意localstorage,因为存储的数据往往会过时。
相反,如果您希望在浏览器会话处于活动状态时保留数据,即在有人关闭浏览器并重新打开它之前,您应该考虑使用与localStorage具有相同语法的sessionStorage
。