我有一个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>
答案 0 :(得分:2)
您使用的是document.getElementById()
,但是输入中没有ID。您的表格应为:
<form id="usrDetails" onclick="return false">
<h1>sign up</h1>
<input type="text" id="Username" name="username" placeholder="Username"/><!--the name attribute describes input name and is used as reference.-->
<input type="text" id="email" name="email" placeholder="Email"/><!--placeholder defines the text to appear in the blank box-->
<input type="password" id="password" name="password" placeholder="Password"/>
<input type="password" id="password2" name="password2" placeholder="Retype Password"/>
<input type="submit" onclick="storeUser();"/>
</form>
还行:
localStorage[usrObject.email] = JSON.stringify(usrObject);
应该是:
localStorage.setItem(usrObject.email, JSON.stringify(usrObject));
...假设您希望电子邮件地址成为存储的用户对象的键。