我想在JavaScript中使用一个函数来捕获表单中的信息 对象,以便我可以将该对象存储在localStorage中。
但是当我使用表单标签时,似乎没有调用该函数。
我是否需要更改表单中的内容或删除表单标记?
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>Test form and localstorage</title>
<script>
function submit(){
var client = {
Name: document.forms['contact']['name'].value,
Age: document.forms['contact']['age'].value,
Sex: document.forms['contact']['sex'].value
}
console.log(client);
localStorage.setItem('client',JSON.stringify(client));
}
</script>
</head>
<body>
<form name = "contact" method = "post" action="#" onsubmit = "submit()">
<table>
<tbody>
<tr>
<td class = "blockSize" id = "td1">Name:</td>
<td class = "blockSize" id = "td2"><input type = "text" name = "name"></td>
</tr>
<tr>
<td class = "blockSize" id = "td3">Age:</td>
<td class = "blockSize" id = "td4"><input type = "text" name = "age"></td>
</tr>
<tr>
<td class = "blockSize" id = "td5">Sex:</td>
<td class = "blockSize" id = "td6"><input type = "text" name = "sex"></td>
</tr>
</tbody>
<button type = "submit">Submit</button>
</table>
</form>
</body>
我需要它只在JavaScript中,所以任何建议都会非常有用。
答案 0 :(得分:1)
最有可能的问题是,您没有阻止onsubmit事件的默认行为。尝试将return false
添加到submit
功能的末尾。
如果您不这样做,表单将尝试POST
信息到它当前所在的页面,这将刷新页面并删除用户的数据。如果要捕获该数据,则需要使用Javascript以外的其他内容。