为什么当我单击表单内的按钮时从未到达提交块

why the submit block is never reached when i click button inside form?

本文关键字:提交 按钮 单击 表单 为什么      更新时间:2023-09-26

我正在nodejs中创建一个聊天应用程序。

在 index.html 文件中,我为用户设置发送消息的接口,我定义了以下形式:

<form id="chat-form" name="chat-form">
     <input type="text" name="chat-input" id="chat-input" placeholder="type message">
     <br>
     <input type="submit" value="send"/>
</form>

<head> </head>标签中,我使用以下脚本:

$('#chat-form').submit(function(e){
    console.log("inside the submit");
});

尽管此代码预期有效,但从未达到提交代码。

如果你在head中调用你的代码,那么代码会在你的html被呈现之前运行,所以在这一点上html表单将不存在。

一般的最佳实践是将javascript代码放在文件的底部,就在结束body标签之前和/或在dom ready函数中运行它。

$(function(){ [code]}); 

上述函数中运行的任何代码都将在 dom 加载后运行,因此您的 html 将在那时存在。

$(function(){
    $('#chat-form').submit(function(e){
        console.log("inside the submit");
    });
});