表单提交输入不是 运行 我的 onClick 函数

Form submit input not running my onClick function

我创建了一个简单的登录表单,并希望在表单提交后 运行 一个 js 函数。但是,当我单击提交时没有任何反应。 HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>CARD GAME</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
<script src="index.js"></script>
<form>
    Username: <input type="text" id="htmlUsername"><br><br>
    Password: <input type="password" id="htmlPassword"><br>
    <input type="submit" onclick="login()">
</form>
</body>
</html>

JS:

function login(){
    console.log("here")
}

我现在在这里看到两件事。

  1. 将包含 js 文件的代码放在 HTML 的底部,就在结束正文标记上方。 <script src="index.js"></script>
  2. 检查您的 JavaScript 文件是否被调用 index.js
  • <input type="submit" onclick="login()">替换为<button type="button" onclick="login()">Login</button>
  • 在表单中添加一个 ID:<form id="myform"> ...

在你的 JS 中做:

function login(){
    alert("here");
    document.querySelector("#myform").submit();
}

当您按下提交按钮时,浏览器 window 是否重新加载?如果是,那么您的表单确实已提交。

您看不到 console.log 语句的输出,因为默认情况下,浏览器 window 在表单提交时重新加载。您可以使用 event.preventDefault()

禁用此默认行为

HTML:

<form>
    Username: <input type="text" id="htmlUsername"><br><br>
    Password: <input type="password" id="htmlPassword"><br>
    <input type="submit" onclick="login(event)">
</form>

JS:

function login(event){
    event.preventDefault();
    console.log("here")
}

改进建议:

  • 不要在 button 元素上使用 onclick 属性,而是使用 .addEventListener() 在按钮上添加点击事件侦听器。

  • script 元素移动到 body 结束标记之前。

备选方案

另一种方法是保留日志。在浏览器开发人员工具的“网络”选项卡中,选中“保留日志”复选框输入。这样做将保留 console.log 语句的输出,即使浏览器 window 在表单提交时重新加载也是如此。

有关如何在开发者工具中启用此选项的详细信息,请访问:

How to enable “Preserve Log” in Network tab in Chrome developer tools by default?

如果您想通过单击 提交 执行某些操作,请在表单标记内声明事件 onsubmit。像这样:

<form onsubmit="login(event);">
...

并添加禁用默认行为 - event.preventDefault()

function login(event){
    event.preventDefault();
    console.log("here")
}

但是我不建议你在html标签内声明js事件。因为这样会导致不好的后果。

试一试:

let form_submit = document.querySelector('form');

form_submit.onsubmit = function(event) {
    event.preventDefault();
    console.log("here");
}

并从 input submit 中删除 onclick="login()"。这里:

<input type="submit" onclick="login()">