2

我有一个页面,其中有一个表单,我附加了一个 jquery 事件处理程序,通过在键盘上按 Enter 来提交此表单。

//Submit form when enter pressed
$(document).keypress(function (e) {
    if (e.which == 13) {
        $('form').submit();
    }
});

我还可以在同一页面上使用 jquery ui dialog() 显示模式。在模态(在调用 dialog() 之前是一个隐藏的 div)中有一个按钮,我还想让用户能够在他按键盘上的 Enter 键时“单击”该按钮。我遇到的问题是,如果我在页面上使用与以前相同的事件处理程序,它将同时提交表单并单击按钮。

我该如何处理,以便第二个事件处理程序仅限于模态/不传播到文档的其余部分?我试过 e.stopPropagation 在那种情况下不起作用。

//Handler on the modal
$(document).keypress(function(e) {
    e.stopPropagation();
    if($('#button-doc-validate').is(':visible') && e.which == 13) {
        //Click the button
        $('#button-doc-validate').click();
    }
});
4

2 回答 2

1

如果您使用 for submit 处理您的表单(它将为您处理 enter 按键)..那么您可以在您的模式上绑定 keypress 事件处理程序以分隔两个不同的按键

$('form').submit(function(){}) //- will handle enter keypress and form submit action

$('modal').keypress(function(){}); //- will handle the keypress inside the modal 

所以输入按键将被分开

http://jsfiddle.net/KMAYv/

于 2012-11-20T15:47:40.327 回答
0

答案很简单,我只是没想到这是可能的。

我刚刚在模态的 div 上绑定了 keypress 事件处理程序,而不是将其绑定到文档:

//Handler on the modal
$('#modal-container').keypress(function(e) {
    if($('#button-doc-validate').is(':visible') && e.which == 13) {
        //Click the button
        $('#button-doc-validate').click();
        return false;
    }
});

这样,它仅在模式上触发并取消返回 false 的传播,因此不会影响更通用的文档范围的按键处理程序。

于 2012-11-20T14:53:11.573 回答