我有一个带有表单的jQuery UI对话框.我想模拟点击对话框中的一个按钮,这样你就不必使用鼠标或制表符.换句话说,我希望它像一个常规的GUI对话框,模拟点击"OK"按钮.

I assume this might be a simple option with the dialog, but I can't find it in the jQuery UI documentation. I could bind each form input with keyup() but didn't know if there was a simpler/cleaner way. Thanks.

推荐答案

我不知道jQuery UI widget中是否有选项,但您可以简单地将keypress事件绑定到包含对话框的div...

$('#DialogTag').keypress(function(e) {
    if (e.keyCode == $.ui.keyCode.ENTER) {
          //Close dialog and/or submit here...
    }
});

This'll run no matter what element has the focus in your dialog, which may or may not be a good thing depending on what you want.

如果希望将其作为默认功能,可以添加以下代码:

// jqueryui defaults
$.extend($.ui.dialog.prototype.options, { 
    create: function() {
        var $this = $(this);

        // focus first button and bind enter to it
        $this.parent().find('.ui-dialog-buttonpane button:first').focus();
        $this.keypress(function(e) {
            if( e.keyCode == $.ui.keyCode.ENTER ) {
                $this.parent().find('.ui-dialog-buttonpane button:first').click();
                return false;
            }
        });
    } 
});

下面是关于它的更详细视图:

$( "#dialog-form" ).dialog({
  buttons: { … },
  open: function() {
    $("#dialog-form").keypress(function(e) {
      if (e.keyCode == $.ui.keyCode.ENTER) {
        $(this).parent().find("button:eq(0)").trigger("click");
      }
    });
  };
});

Jquery相关问答推荐

如何在html css中制作响应表

如何向父元素添加类?

如何定位 prism.js 脚本中包含的代码?

哪个 JQuery Select 器会排除与给定 Select 器匹配的父项的项目?

Ajax 替换而不是追加

jQuery单击/切换两个功能

JQuery/Javascript:判断 var 是否存在

jQuery从字符串中删除字符串

使用 jQuery click 处理锚点 onClick()

jQuery Select 一个具有某个类的div,它没有另一个类

使用 jQuery Select 最后 5 个元素

在 jquery 中启用/禁用下拉框

从父 node 中删除所有子 node ?

将图像 url 转换为 Base64

检测用户是否创建了滚动事件

通过单击按钮获取表格行的内容

如何使用 jQuery 删除 cookie?

Jquery live() 与委托()

更改 div 的内容 - jQuery

如何以编程方式触发 ngClick