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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1464843/
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-26 11:31:33  来源:igfitidea点击:

jQuery UI dialog button text as a variable

jqueryjquery-uivariablesjquery-ui-dialog

提问by crabCRUSHERclamCOLLECTOR

Can anyone tell me how can i use a variable for button text in jQuery UI dialog? I want to make a dynamic button name.

谁能告诉我如何在 jQuery UI 对话框中为按钮文本使用变量?我想制作一个动态按钮名称。

回答by W. van Kuipers

This won't work because of the way jQuery handles the button name (can be with or without quotes)

这将不起作用,因为 jQuery 处理按钮名称的方式(可以带或不带引号)

This will work:

这将起作用:

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 });

回答by crabCRUSHERclamCOLLECTOR

What you can do is assign the button in the dialog an ID and then manipulate it using standard jQuery.

您可以做的是为对话框中的按钮分配一个 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
    }
});

Set button text:

设置按钮文字:

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

回答by David Toy

The problem here is that the dialog plugin does not assign an id to its buttons, so it's quite difficult to modify them directly.

这里的问题是对话框插件没有为其按钮分配 id,因此直接修改它们非常困难。

Instead, initialise the dialog as normal, locate the button by the text it contains and add an id. The button can then be accessed directly to change the text, formatting, enable/disable it, etc.

相反,像往常一样初始化对话框,通过它包含的文本定位按钮并添加一个 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')       

回答by Danny

Maybe I'm missing the point - but wouldn't the easiest way be to use the setter?

也许我没有抓住重点 - 但最简单的方法不是使用二传手吗?

     $("#dialog_box").dialog({
        buttons: {
         [
            text:"OK",
            click: function() {
                //... configure the button's function
            }
         ]
        });

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

回答by Salman A

  1. The button optionin jQuery UI dialog accepts objects and arrays.
  2. The buttons are instances of the button widget. Use the API instead of manipulating the buttons yourself.
  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>

回答by Rahul Varadkar

This can be done in following steps :

这可以通过以下步骤完成:

  1. In JavaScript you can create Array of Buttons.
  2. Set buttons property to the Array of Buttons.
  1. 在 JavaScript 中,您可以创建按钮数组。
  2. 将按钮属性设置为按钮数组。

Following Example explains above steps.

以下示例解释了上述步骤。

  1. Two buttons are defined in btnArray as follows;
  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');
      }
    }
  ];
 var btnArray = [
    { text: "Add Entry",
      click: function(){
        this.retVal = true;
        addRowIntoTemplateManifest();
        $(this).dialog('close');
      }
    },
    { text: "Cancel",
      click: function(){
        this.retVal = false;
        $(this).dialog('close');
      }
    }
  ];

A custom function displayConfirmDialog_Dynamic() is written that accpets, Dialog header, Dialog Text, button Array. The call to this function is as follows:

编写了一个自定义函数 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 );

The function displayConfirmDialog_Dynamic is as follows:

函数 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");  
}

The Confirm Dialog Template is defined as DIV tag as follows. Note that the titleand contents of <p>tag are changed dynamically by JavaScript code.

确认对话框模板定义为 DIV 标签,如下所示。请注意,标记的title和 内容<p>由 JavaScript 代码动态更改。

<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>

The Screenshot of dialog box displayed by above code is shown below:

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

enter image description here

在此处输入图片说明

回答by Egor Pavlikhin

This will work $($("button", $("#dialogId").parent())[NUMBER_OF_YOUR_BUTTON]).text("My Text");

这将工作 $($("button", $("#dialogId").parent())[NUMBER_OF_YOUR_BUTTON]).text("My Text");

回答by Andrew

And don't forget

并且不要忘记

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

回答by Daithí

assign a class to the button. The button text will be in a span with a class called ui-button-textinside your defined class. So if you give your button the class .contacts-dialog-search-buttonthen the code to access the text will be:

为按钮分配一个类。按钮文本将在一个跨度中,ui-button-text在您定义的类中调用一个类。因此,如果您为按钮提供类,.contacts-dialog-search-button则访问文本的代码将是:

$('.ui-button-text','.contacts-dialog-search-button').text();

here is the code I'm using for my current projects buttons, to give you an example.

这是我用于当前项目按钮的代码,给你一个例子。

buttons : [
            {
                text : 'Advanced Search',
                click : function(){
                    if($(this).dialog("option", "width")==290){
                        $('#contacts-dialog-search').show();
                        $(this).dialog("option", "width", 580);
                        $('.ui-button-text','.contacts-dialog-search-button').text('Close Search');
                    }
                    else{
                        $('#contacts-dialog-search').hide();
                        $(this).dialog("option", "width", 290);
                        $('.ui-button-text','.contacts-dialog-search-button').text('Advanced Search');
                    }
                },
                "class" : "contacts-dialog-search-button"
            }
            ]

回答by Ash

Yes completely possible with inline behaviour:

是的,内联行为完全可能:

  1. Create Dialog class with two setter method, setYesButtonName() and setNoButtonName.
  1. 使用两个 setter 方法创建 Dialog 类,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. Create Object of ConfirmDialog class.

     this.CONFIRM_DIALOG = new ConfirmDialog();
    
  2. Call method on any event, let's say onclick()

    OK_DIALOG.setYesButtonName('Wana Marry').showMessage('Worst Idea!!');
    
  1. 创建 ConfirmDialog 类的对象。

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

    OK_DIALOG.setYesButtonName('Wana Marry').showMessage('Worst Idea!!');
    

Job Done!!

任务完成!!