创建日记应用。对本地存储有问题

时间:2019-03-01 03:55:06

标签: jquery html5 local-storage

我正在尝试使用localstorage创建日记应用程序,以将输入的信息保存到文本区域中。当我按下保存按钮时,它将信息保存在正确的框中,但是当我重新加载页面时,所有框的信息都保存在顶部框中。如何编写此代码,以便在重新加载页面时将所有信息保存在正确的框中?

var output_morning=
document.querySelector('.morning');

var input_breakfast=
document.querySelector('.breakfast');

var output_afternoon=
document.querySelector('.afternoon');

var input_lunch=
document.querySelector('.lunch');

var save_button=
document.querySelector('.save-button');


save_button.addEventListener('click', updateJournal);

output_morning.textContent = localStorage.getItem('content');
input_breakfast.value = localStorage.getItem('content');
output_afternoon.textContent = localStorage.getItem('content');
input_lunch.value = localStorage.getItem('content');

function updateJournal(){
localStorage.setItem('content', input_breakfast.value, input_lunch.value);
output_morning.textContent=input_breakfast.value;

output_afternoon.textContent=input_lunch.value;
}
.morning {
	float: left;
	box-sizing: border-box;
	background: #f9f9f9;
	padding: .5rem;
	width: calc(50% - 1rem);
	height: 10rem;
	box-shadow: 0 2px 5px rgba(0, 0, 0, .2);
	color: #202020;
}

.breakfast {
	float: left;
	box-sizing: border-box;
	margin-left: 2rem;
	padding: .5rem;
	width: calc(50% - 1rem);
	height: 10rem;
	border: 1px solid #505050;
	resize: none;
}
.afternoon {
	float: left;
	box-sizing: border-box;
	background: #ff7256;
	padding: .5rem;
	width: calc(50% - 1rem);
	height: 10rem;
	box-shadow: 0 2px 5px rgba(0, 0, 0, .2);
	color: #202020;
}
.lunch {
	float: left;
	box-sizing: border-box;
	margin-left: 2rem;
	padding: .5rem;
	width: calc(50% - 1rem);
	height: 10rem;
	border: 1px solid #505050;
	resize: none;
}
<div class="morning"></div>
<textarea class="breakfast"></textarea>
<div class="afternoon"></div>
<textarea class="lunch"></textarea>
<button class="save-button">save</button>

1 个答案:

答案 0 :(得分:3)

setItem method仅接受两个参数,即键和值。

您可以调用setItem方法两次,以保存两个不同的键值对:

  localStorage.setItem('breakfast', input_breakfast.value);
  localStorage.setItem('lunch', input_lunch.value);

并检索保存的值,例如:

output_morning.textContent = localStorage.getItem('breakfast');
input_breakfast.value = localStorage.getItem('breakfast');
output_afternoon.textContent = localStorage.getItem('lunch');
input_lunch.value = localStorage.getItem('lunch');

An updated demo of your code

或者,您也可以save a JavaScript object in localstorage