具体来说,我不想在按下回车键时使用已经推荐的方法 event.preventDefault()
,因为这至少会破坏 Internet Explorer 中数据列表的功能。
我已经尝试过类似的方法
$("#form").submit(function(event){
console.log(event);
return false; // Allows me to read the console before the form submits!
});
比较事件之间的差异(单击提交按钮与按下回车键),似乎没有什么明显的。我原以为后者会有一个 event.keyCode
,但事实并非如此。
我能想到的一个冗长的解决方法似乎是删除我的提交按钮,并将其替换为一个常规按钮,该按钮的点击必然会提交表单。但那样的话,我将不得不捕获输入中的回车键按下并处理从头开始提交表单。丑陋,但可行。同样,如果可以的话,我不想应用任何preventDefault()
。
最佳答案
一种 hacky 解决方案,但您可以将事件处理程序绑定(bind)到 submit
按钮上的 click
,而不是 submit
#form
。然后您可以检查是否有与事件关联的非零坐标。如果是,则单击 submit
按钮,如果不是,则按下 enter 键。例如
$("input[type='submit']").click(function(event){
if (event.screenX === 0) alert("You hit the enter key!");
else alert("You clicked the submit button!");
return false; // Allows me to read the console before the form submits!
});
关于javascript - 如何区分单击提交按钮和在输入中输入以提交表单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27695606/