更新:
我终于发现“keypress”在Linux 平台上比“keydown”或“keyup”具有更好的兼容性。我只是将“keyup”/“keydown”更改为“keypress”,所以一切顺利。
我不知道是什么原因,但这对我来说是解决方案。感谢所有回答我问题的人。
--
我有一些代码需要使用 JQuery 检测按键事件(我必须知道用户何时按下 Enter),这里是 Javascript 中的代码:
j.input.bind("keyup", function (l) {
if (document.selection) {
g._ieCacheSelection = document.selection.createRange()
}
}).bind("keydown", function(l) {
//console.log(l.keyCode);
if (l.keyCode == 13) {
if(l.ctrlKey) {
g.insertCursorPos("\n");
return true;
} else {
var k = d(this),
n = k.val();
if(k.attr('intervalTime')) {
//alert('can not send');
k.css('color','red').val('Dont send too many messages').attr('disabled','disabled').css('color','red');
setTimeout(function(){k.css('color','').val(n).attr('disabled','').focus()},1000);
return
}
if(g_debug_num[parseInt(h.buddyInfo.id)]==undefined) {
g_debug_num[parseInt(h.buddyInfo.id)]=1;
}
if (d.trim(n)) {
var m = {
to: h.buddyInfo.id,
from: h.myInfo.id,
//stype: "msg",
body: (g_debug_num[parseInt(h.buddyInfo.id)]++)+" : "+n,
timestamp: (new Date()).getTime()
};
//g.addHistory(m);
k.val("");
g.trigger("sendMessage", m);
l.preventDefault();
g.sendStatuses("");
k.attr('intervalTime',100);
setTimeout(function(){k.removeAttr('intervalTime')},1000);
return
}
return
}
}
它在 Windows 上运行良好,但在 Linux 上,有时无法捕获 Enter 事件。有人可以帮忙吗?
更新:
如果我只用英语说话就好了。但是我必须使用一些输入法来输入中文。如果是问题所在? (如果我使用中文输入法,JQuery 无法检测到回车?)
最佳答案
试试这个
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" >
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
</head>
<body>
<div>
<input id="TestTextBox" type="text" />
</div>
</body>
<script type="text/javascript">
$(function()
{
var testTextBox = $('#TestTextBox');
var code =null;
testTextBox.keypress(function(e)
{
code= (e.keyCode ? e.keyCode : e.which);
if (code == 13) alert('Enter key was pressed.');
e.preventDefault();
});
});
</script>
</html>
关于javascript - 在 Javascript 中使用 JQuery 检测按键事件 (Enter)(在 Linux 平台上),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1248100/