我正在尝试使用localstorage创建一个日记应用程序来保存放入textareas的信息。当我按下保存按钮时,它会将信息保存在正确的方框中,但是当我重新加载页面时,所有方框都会从保存在其中的顶部框中获取信息。我如何编写此代码,以便在重新加载页面时将所有信息保存在正确的框中?
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>
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');
作为替代方案,你也可以save a JavaScript object in localstorage