简体   繁体   English

当事件由“ESC”键触发时,表单未在keydown事件中提交

[英]Form not submited on keydown event when event is triggered by 'ESC' key

I need to submit form on hitting the 'ESC' key. 我需要在按下“ESC”键时提交表格。 I have the folowing code to do so: 我有以下代码:

<form id="testForm" name="testForm" method="post" action=""  >
   <input name="givenAnswer" id="realInput"  value="" type="text" onclick="doSubmit()" autofocus>
</form>

<script>
   document.getElementById('realInput').onkeydown = function(e){
       if(e.keyCode == 27){
           event.preventDefault();
           document.testForm.submit();
        }
   };
</script>

but this does not work correctly (I try it with FF 47.0.1): if I type a text to input field, and hit ESC key, form is not submited. 但这不能正常工作(我用FF 47.0.1尝试):如果我输入一个文本输入字段,然后按ESC键,表单不会被提交。 The form is submited on ESC key only in the case I click the input filed by mouse right before I hit ESC key (and this is valid only if line 'event.preventDefault();' is excluded from the script). 只有在我按下ESC键之前单击鼠标右键输入的情况下,才会在ESC键上提交表单(只有在脚本'event.preventDefault();'从脚本中排除时才有效)。 But this is not expected behavoir. 但这不是预期的行为。

The same is with this script: 这个脚本也一样:

<script>
    var el = document.getElementById("realInput");
    el.onkeydown = function(event) {
       if (event.keyCode == 27) {
           document.testForm.submit();
       }
    };
</script>

Would anybody know to tell me what is the problem and suggest solution please? 有人知道告诉我是什么问题并建议解决方案吗?

I foud also these links with similar issue, but the solution proposed there didn't work for me: 我也认为这些链接有类似的问题,但是那里提出的解决方案对我来说不起作用:

location.reload doesn't reload the page when I'm using it in keyDown event handler when ESC is pressed. 当按下ESC时,当我在keyDown事件处理程序中使用它时,location.reload不会重新加载页面。 Only in FF 只在FF

https://bugs.jqueryui.com/ticket/4922 https://bugs.jqueryui.com/ticket/4922

Thanks 谢谢

在您的第一个片段中,只需在event.preventDefault()中将event更改为e

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM