不能在节点js教程中提交表单

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

我在发光事件部分

当我在文本框中键入一条消息,并点击发送它刷新页面,并带我到的URL本地主机:3000 /? 而不是logging在服务器上的消息。

为什么button无法触发$('form')。submit(function(){line?

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

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

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

我已经手中input了所有的东西,但是当它不工作时,我复制粘贴,以确保我是正确的。

所以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位)

尝试将您的代码封装在文档就绪块中。 表单可能还不存在。

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