【发布时间】:2023-03-21 01:46:02
【问题描述】:
我有一个 HTML 注册表单,它接受输入并存储在 JavaScript 数组中,然后使用 JSON.stringify,最后将其存储在本地存储中。问题是密钥是undefined(电子邮件是我的密钥),值是[object Object]。有人可以帮我解决这个问题吗?谢谢?
<!DOCTYPE html>
<html>
<head>
<title>Learning</title>
</head>
<body>
<form id="usrDetails" onclick="return false">
<h1>sign up</h1>
<input type="text" name="username" placeholder="Username"/><!--the name attribute describes input name and is used as reference.-->
<input type="text" name="email" placeholder="Email"/><!--placeholder defines the text to appear in the blank box-->
<input type="password" name="password" placeholder="Password"/>
<input type="password" name="password2" placeholder="Retype Password"/>
<input type="submit" onclick="storeUser();"/> <!--value defines the text to appear on the button-->
</form>
<p id="result"></p>
<script>
function storeUser() {
var usrObject={};
if (document.getElementById("username") !== null) {
usrObject.username = document.getElementById("Username").value;
}
if (document.getElementById("email") !== null) {
usrObject.email = document.getElementById("email").value;
}
if (document.getElementById('password') !== null) {
usrObject.password = document.getElementById("password").value;
}
if (document.getElementById('password2') !== null) {
usrObject.password2 = document.getElementById("password2").value;
}
localStorage.setItem(usrObject.email, usrObject)
JSON.stringify(usrObject);
//localStorage[usrObject.email] = JSON.stringify(usrObject);
document.getElementById("result").innerHTML = "<b>Registration successful</b>"
}
</script>
</body>
【问题讨论】:
-
Javascript 与 Java 无关。他们只共享名称的一部分。
-
如果我从使用 StackOverflow 中学到了什么,那就是人们需要开始学习更多地使用 console.log()。
-
如何修改我的代码来存储 usrObject?我尝试使用 setItem 但它不起作用。我一定是用错了。
标签: javascript arrays json local-storage