在 JavaScript 中重置表单
本教程将教我们如何使用和不使用 jQuery 在 JavaScript 中重置表单。reset()
方法将表单元素恢复为默认值。
JavaScript 中的 reset()
方法的功能与 HTML 重置按钮相同。
对于所有 JavaScript 代码示例,以下 HTML 代码保持不变。
<!DOCTYPE html>
<html>
<body>
<p>
fill the text boxes with some text content and press the "Reset form" button to reset the form.
</p>
<form id="form">
First name: <input type="text" name="firstname"><br>
Last name: <input type="text" name="lastname"><br><br>
<input type="button" onclick="resetForm()" value="Reset form">
</form>
</body>
</html>
在没有 jQuery 的 JavaScript 中重置表单
JavaScript 代码:
function resetForm() {
document.getElementById('form').reset();
}
输出:
上层解决方案是纯 JavaScript。resetForm()
函数在 Reset form
按钮单击时执行。
reset()
方法既不接受参数也不返回任何值。
在 JavaScript 中使用 jQuery 重置表单
请记住将 jQuery 库包含在 <head>
元素中以练习以下代码示例。
JavaScript 代码:
function resetForm() {
$('#form').trigger('reset')
}
输出:
上面的解决方案是用 jQuery 实现的。trigger()
函数触发特定事件和事件的默认行为(如表单提交),用于挑选出的元素。
trigger()
方法类似于 triggerHandler() 函数,除了 triggerHandler()
不会触发事件的默认行为。
以下是我们可以使用的另一个 jQuery 解决方案。它是 document.getElementById("form").reset();
的反映。
JavaScript 代码:
function resetForm() {
$('#form')[0].reset();
}
输出:
请记住,如果表单的任何字段具有属性 name="reset"
,reset()
方法将不起作用。它给你以下错误。
'<a class=\'gotoLine\' href=\'#55:17] Uncaught TypeError: $(...)[0\'>55:17] Uncaught TypeError: $(...)[0</a>.reset is not a function'
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
用 jQuery 检查复选框是否被选中
发布时间:2024/03/24 浏览次数:102 分类:JavaScript
-
在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。