有一个项目名称表和某些按钮,例如新建、编辑和删除。 现在,单击这些按钮,它会打开一个模式,该模式获取信息并其中有一个提交按钮以保存数据库中的更改。
我在本文档中的 switch case 中有一个用于输入键的 keydown 事件,该事件在下一页中显示突出显示的项目行的更多详细信息。
因此,当模式打开时,我通过选项卡按钮快速聚焦到提交按钮,然后单击该聚焦按钮上的 Enter,该项目已提交,但直接打开下一页,其中包含我不知道的所选项目详细信息不想。
我希望当模式打开时,应该阻止文档的 keydown 事件(即不应该工作),并且我应该能够提交模式。
我想我想要的已经很清楚了。因此,如果他们想摆脱困境,请帮助我。我们将不胜感激您的帮助。
这是可以更好地理解它的代码..
$(document).keydown(function(e){
switch(e.which){
/* Enter Key */
case 13:
if(localStorage.check_submit != 1){
location.assign('estimate_partyitems.php'); */
break;
}
}
/* End of Switch Case */
});
/* End of Keydown Event */
$("#btn_new").on("click", function(){
$('#newestimate_modal').on('shown.bs.modal', function () {
// some code
localStorage.check_submit = 1;
});
$('#newestimate_modal').on('hidden.bs.modal', function (e) {
// some code
localStorage.check_submit = 0;
});
/* On Adding the New Estimate */
$('#newestimate_form').submit(function(event){
/*
preventDefault method cancels the event if it is cancelable
Here it is used to prevent the form from submitting.
*/
event.preventDefault();
// some code and ajax requests
/* unbind() method removes event handlers from selected elements. */
$("#newestimate_form").unbind('submit');
});
});
最佳答案
可能可以将其破解到位,但我强烈建议不要这样做,而是在事件处理程序中处理它。类似的东西
let modalOpen = false;
window.onkeydown(e => {
if (!modalOpen) {
// handle the command as normal.
}
});
当然有很多更奇特/更好的方法可以做到这一点,但这是基本思想。 future 的维护者稍后会在尝试找出键绑定(bind)有时神秘地无法触发的原因时感谢您。
下面我编辑了问题的示例代码来反射(reflect)这种新设计。我删除了 localStorage 位,因为它似乎没有做任何事情。 localStorage是一个特殊的对象,它充当一种客户端数据库,以类似于 cookies 的方式持久保存状态。
let modalOpen = false;
$(document).keydown(function(e){
if (!modalOpen) {
switch(e.which){
/* Enter Key */
case 13:
location.assign('estimate_partyitems.php'); */
}
}
/* End of Switch Case */
});
/* End of Keydown Event */
$("#btn_new").on("click", function(){
$('#newestimate_modal').on('shown.bs.modal', function () {
// some code
modalOpen = true;
});
$('#newestimate_modal').on('hidden.bs.modal', function (e) {
// some code
modalOpen = false;
});
/* On Adding the New Estimate */
$('#newestimate_form').submit(function(event){
/*
preventDefault method cancels the event if it is cancelable
Here it is used to prevent the form from submitting.
*/
event.preventDefault();
// some code and ajax requests
/* unbind() method removes event handlers from selected elements. */
$("#newestimate_form").unbind('submit');
});
});
关于javascript - 模态打开时如何防止文档中回车键的keydown事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45125213/