如何通过javascript将待办事项列表数据保存到本地存储中
How to save todo list data with local storage through javascript
这里我只使用javascript。
HTML:
<section class="notes-section">
<div class="layout clearfix">
<input id="user_input" name="user_input" placeholder="Enter your new note" type="text" />
<button value="Add" id="add" onclick="addNotes()">New</button>
<ul id="note_List" class="notes-block"></ul>
</div>
</section>
JavaScript:
<script>
function addNotes() {
var input = document.getElementById('user_input').value;
if (input == "") {
window.alert("You must enter a value in the New Task field.");
}
else {
var noteList = document.getElementById('note_List');
noteList.innerHTML += "<li><span>" + input + "</span><button onclick='this.parentNode.parentNode.removeChild(this.parentNode)' class='delete'>Delete</button> <button class='edit' onclick='this.previousElementSibling.previousElementSibling.contentEditable = true;' >Edit</button></li>";
}
}
</script>
我正在分享小提琴链接:https://jsfiddle.net/o2mLgd67/如果有人可以更新代码,那么这将很有帮助。
我已经尝试了以下代码:
(function() {
var demo = document.querySelector('.notes-block');
function supportsLocalStorage() {
return typeof(Storage)!== 'undefined';
}
if (!supportsLocalStorage()) {
demo.value = 'No HTML5 localStorage support, soz.';
} else {
setInterval(function() {
localStorage.setItem('autosave', demo.value);
}, 1000);
if (localStorage.getItem('autosave')) {
demo.value = localStorage.getItem('autosave');
alert("hi");
}
}
})();
但这对我没有帮助。
在设置值之前,无法从localStorage获取值。
setInterval是异步进程,所以在1000ms后调用"set"语句,但立即调用get。你必须改变它,尝试:
setInterval(function() {
localStorage.setItem('autosave', demo.value);
if (localStorage.getItem('autosave')) {
demo.value = localStorage.getItem('autosave');
alert("hi");
}
}, 1000);
更新:
好的,我纠正您的jsFiddle使用"demo.innerHTML"而不是"demo.value",效果很好!!
请参阅:https://jsfiddle.net/o2mLgd67/7/
setTimeout(function() {
localStorage.setItem('autosave', demo.innerHTML);
demo.innerHTML = "";
setTimeout(function() {
if (localStorage.getItem('autosave')) {
demo.innerHTML = localStorage.getItem('autosave');
alert(demo.innerHTML);
} }, 1000);
}, 1000);
相关文章:
- 如何在服务器上保存数据以备日后使用
- zp.midpass.ru如何在浏览器中保存数据
- Google Chrome扩展在本地保存数据
- Javascript/AngularJS本地保存数据
- jquery ajax到php脚本不保存数据
- 使用LocalStorage保存数据
- jquery保存数据,直到phonegap应用程序关闭
- 以HTML和javascript保存数据
- 单击指向外部网站的链接后,通过MySQL保存数据
- AngularJS:无法保存数据
- 如何在不编码或保存数据的情况下将二进制数据从javascript传递到actionscript(网页到flash)
- 如何在AngularJS中刷新时在服务中持久保存数据
- 如果从浏览器控制台提交,Knockoutjs不会保存数据
- 在nodejs中执行procces数组时保存数据
- MongoDB 在保存数据时抛出错误(拓扑已损坏)
- HTML 在表单之间保存数据
- HTML/JS - 保存数据-* 供以后使用
- 保存数据 asp.net 后单击按钮时显示警报消息
- Chrome 扩展程序保存数据
- 如何在应用程序上保存数据