Dialog keypress and DOM

2019-04-16 18:30发布

I'm trying to use jQuery's keypress to trigger a button click on a modal dialog created using the jQuery dialog function. The problem is, with the following code, it works the first time around (pressing enter presses the Save button) but I get erratic behavior when I close the modal dialog and reopen it. I'm thinking some variant of $(this).("button:contains('Save')") would work, but that doesn't work.

$('#dialog').keypress(function(e) {
        if (e.which == 13) {
      $("button:contains('Save')").click();
        }
});

FYI the dialog is opened using a $("#dialog").dialog('open'), not an autoOpen:true. What would be the best practice for the task?

Thanks!

2条回答
看我几分像从前
2楼-- · 2019-04-16 19:12

I would do:

$('#dialog').keyup(function(e) {
    if (e.which == 13) {
         var buttons = $(this).dialog('option', 'buttons');
         buttons['Save']();
         e.stopPropagation();
    }
})
查看更多
一纸荒年 Trace。
3楼-- · 2019-04-16 19:23

keypress is for letters. keydown is for everything. I would try using keydown.

Your code most likely does not execute. Enter will trigger the default action so that's why it works the first time.

More info here:

http://www.bloggingdeveloper.com/post/KeyPress-KeyDown-KeyUp-The-Difference-Between-Javascript-Key-Events.aspx

查看更多
登录 后发表回答