jquery按键不能使用socket.io

我不知道我在做什么错。 下面的代码只是我尝试过的随机狗屎的最新迭代:

<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{{title}}</title> <link rel="stylesheet" href="../css/home.css"> <script src="//code.jquery.com/jquery-1.11.0.min.js"></script> <script src="/socket.io/socket.io.js"></script> <script> var socket = io(); $(document).ready(function() { $(document).keypress(function(e) { if (e.which == 13) { alert('You pressed enter!'); } }); }); </script> </body> </html> 

我使用的是Firefox。 如果有必要,我会发布app.js,但是我非常确定,使用jQuery来检测button并显示警报是无关紧要的。 我甚至没有使用任何套接字事件。 当我运行的服务器,一切正常,但是当我按下input什么都没有发生。 这是我的app.js:

 var express = require('express'); var app = express(); var http = require('http').Server(app); var path = require('path'); var io = require('socket.io').listen(http); app.set('views', path.join(__dirname, 'views')); app.engine('html', require('hogan-express')); app.set('view engine', 'html'); app.use(express.static(path.join(__dirname, 'public'))); app.get('/', function(req, res){ res.render('index', {title:'test'}); }); http.listen(3000, function(){ console.log('listening on localhost:3000'); }); 

在html文件上缺less</head><body>

我更新了,它为我工作:

 <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{{title}}</title> </head> <body> <link rel="stylesheet" href="../css/home.css"> <script src="//code.jquery.com/jquery-1.11.0.min.js"></script> <script src="/socket.io/socket.io.js"></script> <script> var socket = io(); $(document).ready(function() { $(document).keypress(function(e) { if (e.which == 13) { alert('You pressed enter!'); } }); }); </script> </body> </html> 

更新你的jQuery版本的使用:

 <script src="http://code.jquery.com/jquery-2.1.4.min.js"></script> 

另外删除不需要的$(document).ready({}); function。

使用下面的代码:

 $(document).keydown(function (e) { if (e.which == 13) { alert('You pressed enter!'); } }); 

或者使用这个:

 $(document).bind("keydown",function (e) { if (e.which == 13) { alert('You pressed enter!'); } }); 

检查下面的小提琴:

http://jsfiddle.net/hacker1211/bk56hg5k/