jQuery UI对话框按钮文本作为变量

66

请问如何在jQuery UI对话框中,使用变量作为按钮文本?我想要创建一个动态的按钮名称。


1
很好的问题,我总是觉得缺少这个功能而感到愚蠢,特别是如果你要建立一个多语言网站。 - Francesco
13个回答

102
由于jQuery处理按钮名称的方式(可以带引号也可以不带引号),所以这种方法行不通。
这个将可行:
var button_name = 'Test';
var dialog_buttons = {}; 
dialog_buttons[button_name] = function(){ closeInstanceForm(Function); }
dialog_buttons['Cancel'] = function(){ $(this).dialog('close'); }   
$('#instanceDialog').dialog({ buttons: dialog_buttons });

谢谢。运行得很好。我将在下面添加一个代码示例,以防对任何人有所帮助。 - Grant Johnson

66

你可以给对话框中的按钮分配一个ID,然后使用标准的jQuery进行操作。

$("#dialog_box").dialog({
    autoOpen: false,
    modal: true,
    resizable: false,
    buttons: [{
        text: "Ok",
        "id": "btnOk",
        click: function () {
            //okCallback();
        },

    }, {
        text: "Cancel",
        click: function () {
            //cancelCallback();
        },
    }],
    close: function () {
        //do something
    }
});

设置按钮文本:

 var newLabel = "Updated Label";
 $("#btnOk").html('<span class="ui-button-text">'+ newLabel +'</span>')

1
+1,最后一行代码将是:$("#btnOk").html('<span class="ui-button-text">'+'新标签'+'</span>'); - Alfonso Rubalcava
3
我更喜欢这种方式而不是像W. van Kuipers建议的那样使用单独的函数。 - Ben Sinclair
1
我觉得这对我正在处理的代码更加简洁。谢谢。 - James
在这里,您可以使用vars来设置按钮中的文本。我这样做是为了国际化我的应用程序。在我的php页面(或jsp或其他任何页面)上,您可以设置尽可能多的js vars。在我的情况下,有一个“是”和一个“否”。这些变量由echo设置,该echo执行i18n并在确认框中正确显示。 //编辑=> 这不是重点,是我的错。 - gavard.e
只有在引号中加入"text"后,这个方法才对我起作用。 - Yster

8
这里的问题在于对话框插件没有为其按钮分配id,因此直接修改它们非常困难。
相反,正常初始化对话框,通过其包含的文本查找按钮并添加一个id。然后可以直接访问该按钮以更改文本、格式、启用/禁用等。
$("#dialog_box").dialog({
buttons: {
    'ButtonA': function() {
        //... configure the button's function
    }
});
$('.ui-dialog-buttonpane button:contains(ButtonA)').attr("id","dialog_box_send-button");            
$('#dialog_box_send-button').html('Send')       

$('#dialog_box_send-button').find('.ui-button-text').html('发送'); - DanJ

4
  1. jQuery UI对话框中的按钮选项可以接受对象和数组。
  2. 这些按钮是按钮小部件的实例。使用API而不是自己操纵按钮。

$(function() {
  // using textbox value instead of variable
  $("#dialog").dialog({
    width: 400,
    buttons: [
      { text: $("#buttonText0").val(), click: function() { $(this).dialog("close"); } }, 
      { text: $("#buttonText1").val(), click: function() { $(this).dialog("close"); } }
    ]
  });
  $("#updateButtonText").on("click", function() {
    var $buttons = $("#dialog").dialog("widget").find(".ui-dialog-buttonpane button");
    console.log($buttons.get());

    $buttons.eq(0).button("option", "label", $("#buttonText0").val());
    $buttons.eq(1).button("option", "label", $("#buttonText1").val());

    // few more things that you can do with button widget
    $buttons.eq(0).button("option", "icons", { primary: "ui-icon-check" });
    $buttons.eq(1).button("disable");

    $("#dialog").dialog("open");
  });
});
@import url("https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.min.css");
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>

<div id="dialog" title="Sample Dialog">
  <p>Proceed?</p>
</div>

<p style="text-align: center;">
  <input type="text" id="buttonText0" value="OK">
  <input type="text" id="buttonText1" value="Cancel">
  <input type="button" id="updateButtonText" value="Update Button Text">
</p>


我想强调以下内容; 我认为这是重要的部分:buttons: [ { text: $("#buttonText0").val() }, { text: $("#buttonText1").val() } ]在使用 $(selector).val() 时,您可以在使用“text”选项时放置一个字符串变量,如果尝试以下操作,则无法这样做:confirmStr: function() { $(this).dialog("close"); }, - Mayer M

2
也许我没有理解问题的关键所在 - 但是使用setter难道不是最简单的方法吗?
     $("#dialog_box").dialog({
        buttons: {
         [
            text:"OK",
            click: function() {
                //... configure the button's function
            }
         ]
        });

        $("#dialog_box").dialog("option", "buttons", { "Close": function() { $(this).dialog("close"); } });

1
我已经尝试过这个,但出现了一个问题,它显示的文本是“0”,而不是“Ok”。 - Greg
2
这是最佳实践方法,但你的代码需要修正:buttons 是一个 button 对象数组。你的开头 [ 应该与之前的 { 交换位置,关闭方式同样如此。 - nothingisnecessary

1
这可以通过以下步骤完成:
  1. 在JavaScript中,您可以创建按钮数组。
  2. 将按钮属性设置为按钮数组。
下面的示例说明了上述步骤。
  1. btnArray 中定义了两个按钮,如下所示;
 var btnArray = [
    { text: "Add Entry",
      click: function(){
        this.retVal = true;
        addRowIntoTemplateManifest();
        $(this).dialog('close');
      }
    },
    { text: "Cancel",
      click: function(){
        this.retVal = false;
        $(this).dialog('close');
      }
    }
  ];
一个自定义函数displayConfirmDialog_Dynamic()被编写,它接受对话框标题、对话框文本和按钮数组。调用此函数的方式如下:
displayConfirmDialog_Dynamic("Add Template Manifest Entry?", "Do you want to add following Cuboid Entry to Template Manifest?\nCuboidNane: '" + json.cuboidName + "' CuboidId: " + json.cuboidId + "\non Server:"
+ json.serverUrl , btnArray );

函数displayConfirmDialog_Dynamic的定义如下:
//Confirmation dialog Dynamic Buttons
function displayConfirmDialog_Dynamic(dlgTitle, message, btnArray)
{
    var retVal;
    $("div#dialog-confirm").find("p").html(message);

    var confirmDlg = $( "#dialog-confirm" ).dialog({
          resizable: false,
          height: "auto",
          width: 400,
          modal: true,
          title: dlgTitle,
          buttons: btnArray,
          show:{effect:'scale', duration: 700},
          hide:{effect:'explode', duration: 700}  
    });

    confirmDlg.dialog('option', 'buttons', btnArray);
    confirmDlg.prev(".ui-dialog-titlebar").css({"background":"#ffc000", "color":"#ffffff", "font-size":"13px", "font-weight":"normal"}) ;
    confirmDlg.dialog("open");  
}

确认对话框模板定义为DIV标签,如下所示。请注意,JavaScript代码动态更改title<p>标签的内容。
<div id="dialog-confirm" title="Empty the recycle bin?" style="display:none;">
  <p>These items will be permanently deleted and cannot be recovered. Are you sure?</p>
</div>

以上代码显示的对话框截图如下所示:

enter image description here


1

而且不要忘记

$($("button", $(".info_dialog").parent())[1]).html("<span class='ui-button-text'>Button text here.</span>");

1

这将起作用 $($("button", $("#dialogId").parent())[NUMBER_OF_YOUR_BUTTON]).text("我的文本");


0

使用内联行为完全可以实现:

  1. 创建一个对话框类(Dialog class),其中包含两个setter方法:setYesButtonName()和setNoButtonName()。

        function ConfirmDialog() {
            var yesButtonName = "Yes";
            var noButtonName = "No";
            this.showMessage = function(message, callback, argument) {
                var $dialog = $('<div></div>')
                    .html(message)
                    .dialog({
                        modal: true,
                        closeOnEscape: true,
                        buttons: [
                            {
                                text:yesButtonName,
                                click: function() {
                                    if (callback && typeof(callback) === "function") {
                                        if (argument == 'undefined') {
                                            callback();
                                        } else {
                                            callback(argument);
                                        }
                                    } else {
                                        $(this).dialog("close");
                                    }
                                }
                            },
                            {
                                text:noButtonName,
                                click: function() {
                                    $(this).dialog("close");
                                }

                            }
                        ]
                    });
                $dialog.dialog("open");
            };

            this.setYesButtonName = function(name) {
                yesButtonName = name;
                return this;
            };

            this.setNoButtonName = function(name) {
                noButtonName = name;
                return this;
            };
        }

  1. 创建 ConfirmDialog 类的对象。

     this.CONFIRM_DIALOG = new ConfirmDialog();
    
  2. 在任何事件上调用方法,比如 onclick()。

    OK_DIALOG.setYesButtonName('想结婚').showMessage('最糟糕的主意!!');
    

任务完成了!


0
为什么不用一行代码解决呢...
$("span.ui-button-text:contains('OLD BUTTON NAME')").html('NEW BUTTON NAME');

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接