javascript - 无法在 Node js 教程中提交表单

标签 javascript jquery node.js

我正在做这个 http://socket.io/get-started/chat/

我在“发出事件”部分

当我在文本框中输入消息并点击“发送”时,它会刷新页面并将我带到该网址 本地主机:3000/? 而不是在服务器上记录消息。

为什么按钮无法触发 $('form').submit(function(){ 行?

如果我在chrome上打开JS控制台并输入

socket.emit("chat message", 'testing from console')

它按预期在我的命令行服务器窗口中记录消息。所以我不认为服务器端代码有错误。

我手写了所有内容,但当它不起作用时,我复制粘贴以确保我输入正确。

所以index.html对我来说是

<!doctype html>
<html>
  <head>
    <title>Socket.IO chat</title>
    <style>
      * { margin: 0; padding: 0; box-sizing: border-box; }
      body { font: 13px Helvetica, Arial; }
      form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
      form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
      form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
      #messages { list-style-type: none; margin: 0; padding: 0; }
      #messages li { padding: 5px 10px; }
      #messages li:nth-child(odd) { background: #eee; }
    </style>
    <script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
    <script src="http://code.jquery.com/jquery-1.11.1.js"></script>
    <script>
      var socket = io();
      $('form').submit(function(){
        socket.emit('chat message', $('#m').val());
        $('#m').val('');
        return false;
      });
    </script>
  </head>
  <body>
    <ul id="messages"></ul>
    <form action="">
      <input id="m" autocomplete="off" /><button>Send</button>
    </form>
  </body>
</html>

index.js 是

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http)

app.get('/', function(req, res){
    res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(socket){
  socket.on('chat message', function(msg){
    console.log('message: ' + msg);
  });
});

http.listen(3000, function(){
    console.log('listneing on *:3000')
});

使用 Chrome 版本 47.0.2526.80(64 位)

最佳答案

尝试将代码包装在文档就绪 block 中。该表单可能尚不存在。

$(function(){
     $('form').submit(function(){
           socket.emit('chat message', $('#m').val());
           $('#m').val('');
           return false;
      });
 });

关于javascript - 无法在 Node js 教程中提交表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34377170/

相关文章:

javascript - 使用 mongoose 验证 Express 中的 OTP

javascript - jsPDF 生成内部包含拉伸(stretch)元素的 pdf

Jquery 表排序器和特殊字符

javascript - jQuery - 显示具有多个触发器的多个 div

javascript - jQuery 与其他库冲突

javascript - 自动遍历所有链接的事件

node.js - 通过在 Mongodb 中应用条件,使用 $find 查询嵌套对象

node.js - S3如何查找对象是否具有预签名URL?

javascript - 我需要从网站中选择一个元素 "x",但该网站加载元素“x”太慢

Javascript 正则表达式在数学方程式中查找变量