【问题标题】:How to set a property value based on a variable in Javascript如何根据 Javascript 中的变量设置属性值
【发布时间】:2011-08-18 11:53:16
【问题描述】:

问题是我有这段代码(Jquery UI):

    $("#dialog-confirm").dialog({
        resizable: false,
        modal: true,
        buttons: {
            "Remove": function() {
                $(this).dialog("close");
            },
            "Cancel": function() {
                $(this).dialog("close");
            }
        }
    });

现在我必须通过给每个按钮一个单词翻译来使其国际化。我有变量 STR_REMOVE 和 STR_CANCEL 的翻译,但如果我做类似的事情

        buttons: {
            STR_REMOVE: function() {
                $(this).dialog("close");
            },
            STR_CANCEL: function() {
                $(this).dialog("close");
            }
        }

按钮(属性)取值“STR_REMOVE”和“STR_CANCEL”,而不是其内容。那么问题来了,我该怎么办?

【问题讨论】:

  • 好吧,我对 jQuery UI 不太熟悉,但试试看:buttons[STR_REMOVE] = function() {$(this).dialog("close");} 可能会有帮助。
  • 对象属性不能用对象文字以可变方式定义。 J0HN 的解决方案会有所帮助。 BTW jQuery UI 与此无关。这是一个关于 Javascript 对象定义的问题,应该从问题中删除所有其他内容。

标签: javascript jquery internationalization


【解决方案1】:

试试这个。

var STR_REMOVE = "my delete",  STR_CANCEL = "my cancel";

$("#dialog-confirm").dialog({
    resizable: false,
    modal: true,
    buttons: [{
        text: STR_REMOVE,
        click: function () {
            $(this).dialog("close");
        }
    }, 
    {
        text: STR_CANCEL,
        click: function () {
            $(this).dialog("close");
        }
    }]
});

查看 jquery ui 文档:http://jqueryui.com/demos/dialog/#option-buttons

【讨论】:

  • @naveen:当然,很难在 SO 答案字段中输入代码 ;-)
【解决方案2】:
var buttons = {};
buttons[STR_REMOVE] = function() {
                $(this).dialog("close");
            };
buttons[STR_CANCEL] = function() {
                $(this).dialog("close");
            };
$("#dialog-confirm").dialog({
     resizable: false,
     modal: true,
     buttons: buttons
});

【讨论】:

    【解决方案3】:

    您不能内联执行此操作。您必须先声明对象,然后使用square bracket member operator 设置属性:

    var buttons = {};
    buttons[STR_REMOVE] = function() {
        $(this).dialog("close");
    };
    buttons[STR_CANCEL] = function() {
        $(this).dialog("close");
    };
    
    $("#dialog-confirm").dialog({
        resizable: false,
        modal: true,
        buttons: buttons
    });
    

    【讨论】:

    • 事实上你可以这样做。查看挡泥板答案
    • @naveen 很公平——有一个 jQuery UI 解决方案。不过,我已经展示了使用对象文字完成 OP 想要的唯一方法。
    【解决方案4】:

    试试这个,未测试:

    $("#dialog-confirm").dialog({
        resizable: false,
        modal: true,
        buttons: {
            "Remove": function() {
                $(this).html(STR_REMOVE);
                $(this).dialog("close");
            },
            "Cancel": function() {
                $(this).html(STR_REMOVE);
                $(this).dialog("close");
            }
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2011-06-07
      • 2011-11-27
      • 1970-01-01
      • 2022-11-21
      • 1970-01-01
      • 2022-01-10
      • 2022-09-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多