我不希望我在 Stackoverflow 上的第一篇文章成为一个问题,但我是编码新手,需要一点帮助。我正在尝试使用 localStorage 数据填充我的表单字段,以便可以对其进行编辑。我整天都在这。不知道如何正确发布我的代码,所以就到这里。
它不断抛出“无法读取“1”的属性的错误。我确实得到了要填写的表单,但它填充了“[object HTMLInputElement]”任何帮助将不胜感激,谢谢
$("#save").click(function (e) {
alert("Name Has Been Saved");
e.preventDefault();
var data = $("#form").serializeArray();
var id = Math.floor(Math.random() * 10000001);
var item = {};
item.first = ["First:", $("#first").val()];
item.last = ["Last:", $("#last").val()];
$.each(data, function (i, obj) {
localStorage.setItem(id, JSON.stringify(item));
});
});
//Fill with data from localstorage to edit
function editItem(){
var value = localStorage.getItem(this.key);
var item = JSON.parse(value);
$("#form").show(function () {
$("#userDiv").hide(function () {
});
});
$("#first").val(item.first[1]);
$("#last").val(item.last[1]);
}
});
});
function deleteItem() {
var ask = confirm("Are you sure you want to delete this contact?");
if (ask) {
localStorage.removeItem(this.key);
alert("Contact was deleted!!");
window.location.reload();
} else {
alert("Contact was NOT deleted.");
}
}
$("#clear").click(function (e) {
e.preventDefault();
if(localStorage.length === 0){
alert("There Is No Info To Clear")
}else{
localStorage.clear();
alert("All Names Have Been Deleted!");
window.location.reload();
return false;
}
});
});
});
<div data-role="page" id="home" data-theme="b">
<form id="form">
<label>First<input type="text" name="First" id="first"></label>
<label>Last<input type="text" name="Last" id="last"></label><br>
<input type="submit" value="Save" id="save"/>
<input type="submit" value="Clear" id="clear"/>
<input type="submit" value="Show" id="show"/>
</form>
<ul id="userDiv">
<a href="#home" data-role="button" data-mini="true" data-inline="true">to form</a>
</ul>
</div>