我有一个AJAX-y类型的页面。当用户点击“GO”时,我需要执行特定的javascript函数。当用户点击“Enter”或“Return”时,我也想模拟“GO”点击。请注意我不想“提交”页面。原因是因为我通过JavaScript做所有事情。
要处理“输入”/“返回”键,请按IE和FireFox,我使用以下代码:
$(document).ready(function () {
$('#root').keypress(function(e) {
if (e.keyCode == '13') {
goButton();
}
});
});
很遗憾,此代码无法在Chrome中运行。调用goButton()函数。但问题是页面被提交了。我做错了什么?
答案 0 :(得分:6)
假设你有一个表格:
$('#theForm').submit(function(e){
e.preventDefault();
goButton();
return false; // just to be sure.
});
您需要阻止表单中的提交事件,当表单具有焦点并且用户按下回车时将调用该事件。
答案 1 :(得分:3)
我同意BGerrissen,这是最好的方法。但是,为了更好地适应您的代码,您只需将停靠点添加到当前函数中:
$(document).ready(function () {
$('#root').keypress(function(e) {
if (e.keyCode == '13') {
e.preventDefault();//Stops the default action for the key pressed
goButton();
return false;//extra caution, may not be necessary
}
});
});
答案 2 :(得分:0)
尝试在if语句(调用goButton())之后直接返回false。
请在此处查看示例:Using jQuery to prevent form submit when enter is pressed