您好,每次我填写表单并单击提交时,我都需要一些帮助来将新对象添加到本地存储,我想将新项目添加到本地存储,这可能吗?请对我的下面的代码提出建议和/或帮助。谢谢您的帮助。每次当我从下拉值中选择时。
我的下拉表单:
<form asp-action="Create">
<div asp-validation-summary="All" class="text-danger"></div>
<div class="form-group">
<label asp-for="ScheduleStartTime" class="control-label"></label>
<input asp-for="ScheduleStartTime" class="form-control" id="scheduleStartTime" />
<span asp-validation-for="ScheduleStartTime" class="text-danger"></span>
</div>
<select asp-for="CandidateID" class="form-control" id="candId">
@{
if (candidates != null)
{
foreach (var cand in candidates)
{
<option value='@cand.ID'>@cand.DisplayName</option>
}
}
}
</select>
<div class="form-group">
<input onclick="addTheEvent(); return false;" type="submit" value="Add " class="btn btn-primary" />
</div>
</form>
这是我的代码:
<script>
var addToTheContent = document.getElementById("canvas");
var scheduleEvent = document.getElementById("scheduleStartTime");
var candidateId = document.getElementById('candId');
var getCandId = document.getElementById("candId");
var displayCandId = getCandId.options[getCandId.selectedIndex].value;
function addTheEvent() {
var showText = addToTheContent.innerHTML = displayCandId + " ( " + scheduleEvent.value + " ) ";
localStorage.setItem("key", showText)
localStorage.getItem("key");
}
</script>
更新:
function addTheEvent() {
var showText = addToTheContent.innerHTML = displayCandId + " (" + scheduleEvent.value + ") ";
//set value into local storage
localStorage.setItem("key", JSON.stringify(showText));
localStorage.getItem('key');
// localStorage.getItem("key") // get value from localStorage
window.location.href = "/";
}
最佳答案
要将对象保存在 localStorage 中,请尝试以下操作:
let user = {
name: "Ivan",
surname: "Petrov"
}
//save data
localStorage.setItem('user', JSON.stringify(user))
//get data
let user = JSON.parse(localStorage.getItem('user'))
关于javascript - 如何在javascript中将新对象添加到本地存储?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60959443/