我正在尝试控制整个表单的日志,但JavaScript代码太长了。谁能帮助我如何关注干(不要重复自己),因为我在我的脚本标签中重复了很多代码
<form class="form" action="register.jsp" method="post">
<ul class="fieldlist">
<li>
<label for="simple-input"> UserName < /label> < input id="simple-input1" name="userid" type="text" class="k-textbox" style="width: 100%;" />
</li>
<li>
<label for="simple-input">Password</label>
<input id="simple-input2" name="pwd" type="password" class="k-textbox" style="width: 100%;" />
</li>
<li>
<input onclick="myFunction()" id="button" type="submit">
</li> </ul>
</form>
这是我的脚本标签。我想遵循DRY规则。我已经尝试将值保存到每个单独的变量中。
<script>
var nameInput = document.getElementById('simple-input1');
document.querySelector('form.form').addEventListener('submit', function(e) {
//prevent the normal submission of the form
e.preventDefault();
console.log("Username: " + nameInput.value);
});
var nameInput1 = document.getElementById('simple-input2');
document.querySelector('form.form').addEventListener('submit', function (e) {
//prevent the normal submission of the form
e.preventDefault();
console.log("Password: " + nameInput1.value);
});
</script>
您可以使用document.querySelector('form.form').elements
获取表单元素
document.querySelector('form.form').addEventListener('submit', function(e) {
e.preventDefault();
let x = document.querySelector('form.form').elements;
console.log("Username: ", x['userid'].value);
console.log("Password: ", x['pwd'].value);
});
<form class="form" action="register.jsp" method="post">
<ul class="fieldlist">
<li>
<label for="simple-input"> UserName</label>
<input id="simple-input1" name="userid" type="text" class="k-textbox" style="width: 100%;">
</li>
<li>
<label for="simple-input">Password</label>
<input id="simple-input2" name="pwd" type="password" class="k-textbox" style="width: 100%;">
</li>
<li>
<input id="button" type="submit">
</li>
</ul>
</form>
你的听众都在听同样的事情 - 提交。通过使用模板文字和console.log()
的换行符将它们合并为简化的侦听器,使代码更简单:
document.querySelector("form.form").submit = function(e) {
e.preventDefault();
console.log(`Username: ${nameInput.value}\nPassword: ${nameInput1.value}`);
}
你可以使用FormData
并传递form
元素作为参数。然后使用FormData.entries()
获取所有值的迭代器
document.querySelector('form.form').addEventListener('submit', function(e) {
e.preventDefault();
const formData = new FormData(this);
const entires = formData.entries();
for (var input of entires) {
console.log(input[0] + ': ' + input[1]);
}
});
<form class="form" action="register.jsp" method="post">
<ul class="fieldlist">
<li>
<label for="simple-input"> UserName </label> <input id="simple-input1" name="userid" type="text" class="k-textbox" style="width: 100%;" />
</li>
<li>
<label for="simple-input">Password</label>
<input id="simple-input2" name="pwd" type="password" class="k-textbox" style="width: 100%;" />
</li>
<li>
<input id="button" type="submit">
</li>
</ul>
</form>