Javascript jquery-ui Dialog:将对话框中的按钮设为默认操作(回车键)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2522125/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:43:52  来源:igfitidea点击:

jquery-ui Dialog: Make a button in the dialog the default action (Enter key)

javascriptjqueryjquery-uimodal-dialog

提问by fgui

In a jquery modal dialog, is there a way to select a button as the default action (action to execute when the user presses enter)?

在 jquery 模态对话框中,有没有办法选择一个按钮作为默认操作(用户按下 Enter 时执行的操作)?

Example of jquery web site: jquery dialog modal message

jquery 网站示例: jquery 对话框模态消息

In the example above the dialog closes when the user presses Esc. I would like the "Ok" button action to be called when the user presses Enter.

在上面的例子中,当用户按下 Esc 时对话框关闭。我希望在用户按 Enter 时调用“确定”按钮操作。

采纳答案by Nick Craver

In your dialog's open function, you can focus the button:

在对话框的打开函数中,您可以聚焦按钮:

$("#myDialog").dialog({
    open: function() {
      $(this).parents('.ui-dialog-buttonpane button:eq(0)').focus(); 
    }
});

Change the :eq(0)if it's at a different index, or find by name, etc.

更改:eq(0)它是否位于不同的索引,或按名称查找等。

回答by Eugenio Miró

I like this one (it is working for me), which leaves the focus where I wanted to be (a text box)

我喜欢这个(它对我有用),它将焦点留在了我想要的地方(一个文本框)

    $("#logonDialog").keydown(function (event) {
        if (event.keyCode == $.ui.keyCode.ENTER) {
            $(this).parent()
                   .find("button:eq(0)").trigger("click");
            return false;
        }
    });

However, this is working just for one button (Ok button), if needed ':eq(n)' could be set to select other button.

但是,这仅适用于一个按钮(确定按钮),如果需要,可以将 ':eq(n)' 设置为选择其他按钮。

Note:I added a new line returning false to prevent event bubbling when the enter key is handled, I hope it helps better than before.

注意:我添加了一个返回 false 的新行,以防止在处理 Enter 键时出现事件冒泡,我希望它比以前更好用。

回答by madeuz

try this way:

试试这个方法:

$("#myDialog").dialog({
    open: function() {
         $(this).siblings('.ui-dialog-buttonpane').find('button:eq(1)').focus(); 
    }
});

回答by Thomas

This other stackoverflow questionshould get you where you want:

这个其他stackoverflow问题应该可以让你到达你想要的地方:

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

回答by Mark B

Another option that gives you more control over all buttons in the dialog is to add them as an array of buttons. Then in the open eventyou can get the buttons by id and do whatever you want (including set the focus)

另一个可以让您更好地控制对话框中所有按钮的选项是将它们添加为按钮数组。然后在open 事件中,您可以通过 id 获取按钮并做任何您想做的事情(包括设置焦点

$('#myDialog').dialog({
    buttons: [  
                {
                    id: "btnCancel",
                    text: "Cancel",
                    click: function(){
                        $(this).dialog('close');
                    }
                },
                {
                    id: "btnOne",
                    text: "Print One",
                    click: function () {
                        SomeFunction(1);
                    }
                },
                {
                    id: "btnTwo",
                    text: "Print Two",
                    click: function(){
                        SomeFunction(0);
                    }
                }
            ],
    open: function () {
        if ($('#hiddenBool').val() != 'True') {
            $('#btnOne').hide();
        }
        $("#btnTwo").focus();
    }
});

回答by matt burns

A slight variation to use the buttons name as the selector. It reads a little better but there is obvious duplication with the button text string. Refactor to taste.

使用按钮名称作为选择器的细微变化。它读起来好一点,但按钮文本字符串有明显的重复。重构以品尝。

$("#confirm-dialog").dialog({
    buttons: {
        "Cancel" : function(){},
        "OK" : function(){}
    },
    open: function() {
        $(this).siblings('.ui-dialog-buttonpane').find("button:contains('OK')").focus(); 
    }
});

回答by Darren

The simplest way would be to use the submit action on a form within the dialog, however:

最简单的方法是在对话框中的表单上使用提交操作,但是:

  • I did not want to require a form within dialog (N.B. different browsers handle the enter key differently, and some do not always do a submit on enter).
  • I wanted this to work if the user clicks in the title pane or button pane prior to pressing enter.
  • I wanted to make a library method that I can use for ANY jQueryUI dialog.
  • 我不想在对话框中需要一个表单(注意不同的浏览器处理回车键的方式不同,有些浏览器并不总是在回车时提交)。
  • 如果用户在按 Enter 键之前单击标题窗格或按钮窗格,我希望此功能起作用。
  • 我想制作一个可以用于任何 jQueryUI 对话框的库方法。

The company I work for is 'EBL' and I avoid global scope...hence the prefix on the functions below:

我工作的公司是“EBL”,我避免使用全局范围……因此以下函数的前缀:

EBL.onUiDialogOpen = function (event, ui, hideX, actionFirstButtonOnEnterKey) {

    if (hideX) {
        // There is no option to hide the 'X' so override.
        $(".ui-dialog-titlebar-close").hide();
    }

    if (actionFirstButtonOnEnterKey) {
        /* (event.target) will give the div that will become the content 
        of a UI dialog, once div is 'opened' is it surrounded by a 
        parent div that contains title and buttonpane divs as well as 
        content div - so I use .parent()

        ...The keyup function is binded to all descendants, therefore:
              -We need the e.stopPropagation() line.
              -This code is NOT what you want if you DON'T want enter 
               key to initiate first button regardless of selected control.
        */
        $(event.target).parent().bind('keydown.justWhileOpen', function (e) {
            if (e.keyCode === $.ui.keyCode.ENTER) {
                e.stopPropagation();
                $(event.target).next('.ui-dialog-buttonpane')
                    .find('button:first').click();
            }
        });
    }
};

...works in combination with:

...结合使用:

EBL.onUiDialogClose = function (event, ui) {
    // Remove keyup handler when we close dialog
    $(event.target).parent().unbind('.justWhileOpen');
};

You do not need the .onUiDialogClose if you are using a dynamically created div and destroying it afterwards.

如果您使用动态创建的 div 并在之后销毁它,则不需要 .onUiDialogClose 。

You can see below how I use these library functions when initialising a non-dynamic dialog...

您可以在下面看到我在初始化非动态对话框时如何使用这些库函数...

$('#divName').dialog({
    //...
    open: function (event, ui) { EBL.onUiDialogOpen(event, ui, false, true); },
    close: function (event, ui) { EBL.onUiDialogClose(event, ui); },
    //...
});

So far I have tested this in IE9 and latest chrome/firefox. You should validate the dialog as neccessary in your 'Ok' function.

到目前为止,我已经在 IE9 和最新的 chrome/firefox 中对此进行了测试。您应该在“确定”功能中根据需要验证对话框。

回答by Niklaus

I'm using version 1.10.0. I could not get it to work with open but with focus. This focuses the second button:

我正在使用 1.10.0 版。我无法让它以开放但专注的方式工作。这将聚焦第二个按钮:

focus: function(){
  $(this).siblings('.ui-dialog-buttonpane').find('button:eq(1)').focus();
}

回答by Naveen

$("#logonDialog").keydown(function (event) {if (event.keyCode == 13) {
        $(this).parent().find("button:eq(0)").trigger("click");
        return false;
    }
});

回答by uksitebuilder

This worked for me within the dialog using jquery 1.10.2

这在使用 jquery 1.10.2 的对话框中对我有用

dialog({
    focus: function() {
        $(this).on("keyup", function(e) {
            if (e.keyCode === 13) {
                $(this).parent().find("button:eq(1)").trigger("click");
                return false;
            }
        });
    },

more options...

更多选择...