preventDefault() 是一个 JavaScript 函数,用于阻止表单的默认提交行为
以下是如何在表单提交中使用 preventDefault() 的示例:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Form Submission Example</title></head><body> <form id="myForm"> <label for="username">Username:</label> <input type="text" id="username" name="username" required> <button type="submit">Submit</button> </form> <script src="https://www.mykuaidi.com/static/image/lazy.gif" class="lazy" original="https://www.mykuaidi.com/static/image/nopic320.png">接下来,创建一个名为 script.js 的 JavaScript 文件,并添加以下代码:document.addEventListener('DOMContentLoaded', function () { const form = document.getElementById('myForm'); form.addEventListener('submit', function (event) { // Prevent the default form submission behavior event.preventDefault(); // Get the username value from the input field const username = document.getElementById('username').value; // Perform your custom logic here, e.g., send the data to a server, display a message, etc. alert(`Username submitted: ${username}`); });});在这个示例中,我们首先等待文档内容加载完成,然后获取表单元素并为其添加一个 ‘submit’ 事件监听器。当表单提交时,我们调用 event.preventDefault() 来阻止默认的提交行为。接下来,我们可以执行自定义逻辑,例如发送数据到服务器或显示一条消息。


