我目前正在像这样将值输入本地存储
<form name="myform" action="" method="GET">
Event Name: <INPUT TYPE="text" NAME="name" VALUE="" id="input1"><br />
Event Date and Time: <INPUT TYPE="datetime-local" NAME="date" Value="" id="input2"><br />
Event Location: <INPUT TYPE="text" NAME="location" VALUE="" id="input3"><br />
Event Notes: <INPUT TYPE="text" NAME="notes" VALUE="" id="input4"><br />
<button onclick="storeValues(event)" type=submit>Submit</button>
</form>
<script>
function storeValues(e) {
e.preventDefault();
let storedEvents = JSON.parse(localStorage.getItem("Events")) || [];
const newEventDetails = {
name: document.getElementById('input1').value,
dateTime: document.getElementById('input2').value,
location: document.getElementById('input3').value,
notes: document.getElementById('input4').value
}
storedEvents.push(newEventDetails);
localStorage.setItem("Events", JSON.stringify(storedEvents));
console.log('storedEvents', storedEvents);
}
</script>
但是我发现我目前无法实现从本地存储输出多个值。
<h2 class="title">Upcoming Events</h2>
<h3 id='input1'> </h3>
<h3 id='input2'> </h3>
<h3 id='input3'> </h3>
<h3 id='input4'> </h3>
<!-- running script here will populate H2's with values from local storage -->
<script>
document.getElementById('input1').innerText = localStorage.getItem('EventName');
document.getElementById('input2').innerText = localStorage.getItem("EventDateAndTime");
document.getElementById('input3').innerText = localStorage.getItem("EventLocation");
document.getElementById('input4').innerText = localStorage.getItem("EventNotes");
</script>
如何使用这些字段显示最新输入,然后在另一页上显示所有先前输入?
答案 0 :(得分:1)
您当前的代码无效,因为您正在从本地存储的EventName
,EventDateAndTime
等属性中检索项目,但是您从未保存到这些属性,因此它们将是{ {1}}。
您将所有事件信息存储在单个属性null
中,该属性包含添加新事件时要推送到的数组。因此,要显示保存的最后一项,您只需访问数组中的第一项,并显示保存的先前项,只需访问数组中的相应先前索引:
localStorage.Events
const renderEvent = (event) => {
document.getElementById('input1').textContent = event.name;
document.getElementById('input2').textContent = event.dateTime;
document.getElementById('input3').textContent = event.location;
document.getElementById('input4').textContent = event.notes;
};
// Display last event:
const storedEvents = JSON.parse(localStorage.getItem("Events"));
if (!storedEvents) throw new Error('No events');
const lastEvent = storedEvents.pop();
renderEvent(lastEvent);