【问题标题】:jquery-ui Dialog: Make a button in the dialog the default action (Enter key)jquery-ui Dialog:使对话框中的按钮成为默认操作(Enter 键)
【发布时间】:2010-03-26 09:23:34
【问题描述】:

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

jquery 网站示例: jquery dialog modal message

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

【问题讨论】:

标签: javascript jquery jquery-ui modal-dialog


【解决方案1】:

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

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

如果 :eq(0) 位于不同的索引处,则更改它,或者按名称查找等。

【讨论】:

  • 我刚刚写了代码来使用 $(this).parent().find('button:nth-child(1)').focus();这是相似的。谢谢
  • 是的,我确实打开了:function() { $(this).parent().find('.ui-dialog-buttonpane button:eq(1)').focus(); }.
  • 我认为这种方法不适用于较新版本的 jQuery UI。对话框的 DOM 现在似乎将 div.ui-dialog-buttonpane 作为同级,而不是 $(this) 的父级。在下面查看madeuz的答案。 zesc 的答案将包括对话框的标题栏“x”。 Gabriel的答案和madeuz的基本一样,只是遍历有点不同。
  • 任何对 keycode 13 使用事件处理程序的答案都比这更好,因为这仅在您只有按钮时才有效。如果您想将焦点设置为与默认按钮不同的控件,这将不起作用。达伦斯回答使用带有提交操作的表单也可能是一个更好的回答。
  • 我发现它有效,但设置焦点与将按钮设为默认值不同。如果 div 中还有其他控件,那么一旦它们被选中,按钮将不再具有焦点?确定需要 keydown 事件吗?
【解决方案2】:

我喜欢这个(它对我有用),它将焦点留在我想要的位置(文本框)

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

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

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

【讨论】:

  • 这是要走的路。设置焦点(如其他解决方案所示)会使使用 tab 转到其他字段但仍想在表单中的任何位置点击“输入”的高级用户搞砸。
  • 最好使用which而不是keyCode。
  • 为了让它工作,我不得不将动作线更改为:$(this).parent().find('button:nth-child(1)').click(); 看起来更近的元素已经占据了第零位!
【解决方案3】:

试试这个方法:

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

【讨论】:

  • 这似乎与较新版本的 jQuery UI(在 1.9.2 中测试)创建的 DOM 相匹配。查看 jsfiddle.net/KF3pp/1 以获取不涉及 :eq(x) 的模式
  • 另外,我相信这将适用于任何版本的 jQuery UI: $(this).parents('.ui-dialog').find('.ui-dialog-buttonpane button:eq( 0)') .
  • 这在 jQuery UI 1.10 中也适用于我。接受的答案没有。
【解决方案4】:

This other stackoverflow question 应该可以带你去你想去的地方:

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

【讨论】:

  • 在发布这个问题之前我没有找到这个问题。这绝对是几乎相同的问题。感谢您指出。我试图让这段代码工作但没有取得多大成功。我尝试下载最新版本的 jqueryui 并将此代码添加到示例 (index.html) 中,但没有成功。
【解决方案5】:

另一个让您可以更好地控制对话框中所有按钮的选项是将它们添加为按钮数组。然后在 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();
    }
});

【讨论】:

  • 我无法获得 $("#btnTwo").focus();工作以聚焦按钮。哎呀。我的错。确实如此!
【解决方案6】:

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

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

【讨论】:

    【解决方案7】:

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

    • 我不想要求对话框中的表单(注意,不同的浏览器处理回车键的方式不同,有些浏览器并不总是在回车时提交)。
    • 如果用户在按 Enter 之前单击标题窗格或按钮窗格,我希望它能够正常工作。
    • 我想做一个库方法,我可以用于任何 jQueryUI 对话框。

    我工作的公司是“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();
                }
            });
        }
    };
    

    ...结合使用:

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

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

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

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

    到目前为止,我已经在 IE9 和最新的 chrome/firefox 中对此进行了测试。 您应该在“确定”函数中验证对话框是否必要。

    【讨论】:

    • 您可以在 JQuery 站点中使用以下 CSS 隐藏 close-X:.no-close .ui-dialog-titlebar-close { display: none; },然后像这样设置对话框的样式:$( "#dialog" ).dialog({ dialogClass: "no-close", ...
    【解决方案8】:

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

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

    【讨论】:

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

      【讨论】:

        【解决方案10】:

        这在使用 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;
                    }
                });
            },
        

        更多选项...

        【讨论】:

          【解决方案11】:

          这段简单的代码为您的按钮设置样式并将默认设置为最后一个:

           open: function(){
          
                $buttonPane = $(this).next();
                $buttonPane.find('button:first').addClass('accept').addClass('ui-priority-secondary');
                $buttonPane.find('button:last').addClass('cancel').addClass('ui-state-default');
                $buttonPane.find('button:last').focus();
          
            },
          

          【讨论】:

          • 如果在 jquery ui 对话框的上下文中,这个答案可能会得到改进。
          【解决方案12】:

          在我的例子中,没有一个答案有效,因为我在一个空的 div 上调用了 .dialog 并添加了我的按钮动态,所以 $(this).html() 不会返回任何内容.所以我不能调用像parent() 或siblings() 这样的方法并期望得到回报。我所做的是直接选择ui-dialog-buttonpane 类并从那里找到按钮元素

          HTML

          <div id = "dialogexample">
          </div>
          

          jQuery

          $("#dialogexample").dialog({
              autoOpen: false,
              modal: true,
              open: function () {
                  $('.ui-dialog-buttonpane').find('#otherbutton').focus();
              }
          });
          var buttons = {
              "MyButton" : {
                  text: "Do Stuff",
                  id: "dostuffbutton" 
              },
              "OtherButton" : {
                  text: "Other Stuff",
                  id: "otherbutton"
              }
          } 
          $("#dialogexample").dialog("option", "buttons", buttons);
          $("#dialogexample").dialog("open"); //the second (otherbutton), instead of
                                              //the first (dostuffbutton) button should be focused
          

          【讨论】:

            【解决方案13】:

            我知道这是一个旧线程,但我一直在寻找这个确切的功能,并且能够实现我认为最好的解决方案,因为我发现以上所有内容都有点不足。

            它是上面两个答案的组合。使用 ID 而不是依赖 find() 函数来查找按钮元素对我来说似乎总是一个更好的选择。

            如果需要,还可以显式查找要按下的回车键,这样我们可以在打开对话框时将焦点设置到我们想要的任何元素。这似乎允许最大的灵活性,同时满足在按下回车键时将特定按钮作为“默认”触发的愿望。我还实现了“取消”默认值。

            我希望这可以帮助其他人寻找一个好的对话框“默认”按钮解决方案。

            $("#LoginBox").dialog({
               open: function(){
                  $(this).keydown(function (event) {
                     if (event.keyCode == 13) {
                        $("#LogInButton").trigger("click");
                        return false;
                     }
                     if (event.keyCode == 27) {
                        $("#CancelButton").trigger("click");
                        return false;
                     }
                  });
               },
               close: function(){
                  $(this).dialog("destroy");
               },
               buttons: [
                  {
                     id: "LogInButton",
                     text: "Log In",
                     click: function(){
                        //button functionality goes here
                        $(this).dialog("destroy");
                     }
                  },
                  {
                     id: "CancelButton",
                     text: "Cancel",
                     click: function(){
                        $(this).dialog("destroy");
                     }
                  }
               ]
            });
            

            【讨论】:

              【解决方案14】:

              您应该使用 :tabbable 选择器和按钮的索引(0 是 [X] 按钮,您的从 1 开始)

              open: function() {
                  var tb = $(":tabbable", this.parentNode);
                  if(tb.length>1) {
                      tb[1].focus();
                  }
              }
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2016-04-23
                • 2013-12-14
                相关资源
                最近更新 更多