简体   繁体   English

我可以在Javascript / jQuery中使用变量作为键吗?

[英]Can I use a variable as a key in Javascript/jQuery?

Basic Javascript/jQuery question: How can I use a nonliteral for the key in a key/value pair? 基本的Javascript / jQuery问题:如何在键/值对中使用非智能键? I thought the following syntax (below) would parse, but it does not. 我认为以下语法(下面)会解析,但事实并非如此。 I am trying to make a dialog that is dynamic. 我正在尝试创建一个动态的对话框。 I want the button text to be variable. 我希望按钮文本是可变的。 How can I do this with Javascript/jQuery? 我怎么能用Javascript / jQuery做到这一点? Or do I have to invoke PHP on my .js file? 或者我必须在我的.js文件上调用PHP? (So don't want to do this...) (所以不想这样做......)

function see_menu_custom(t1, m1, t2, m2, t3, m3, t4, m4, t5, m5)
{   
    $(document).simpledialog2(
    { 
        mode: 'button',
        headerText: 'Send Message',
        headerClose: true,
        showModal: true,
        animate: false,
        buttons :
        {
            t1: /******** How can I make this a nonliteral? *********/
            {
                click: function () { 
                    sendMessage(username, token, t1, m1);
                },
                iconpos : "right",
                icon : "arrow-r",
                theme : "e"
            },
...

使用括号表示法

buttons[var] = {};

Bracket notation is the right answer, but as you seem to be asking how to pass it, too, construct like this 括号表示法是正确的答案,但是你似乎也在问如何传递它,这样构造

function see_menu_custom(t1, m1, t2, m2, t3, m3, t4, m4, t5, m5)
{   
    var myButtons = {};
    myButtons[t1] = {
        click: function () { 
            sendMessage(username, token, t1, m1);
        },
        iconpos : "right",
        icon : "arrow-r",
        theme : "e"
    };
    // rest of buttons
    ...
    // then pass into next step
    $(document).simpledialog2(
    { 
        mode: 'button',
        headerText: 'Send Message',
        headerClose: true,
        showModal: true,
        animate: false,
        buttons : myButtons, // here
...

您只能使用字符串作为对象文字,要使用表达式,您必须使用方括号和赋值:

buttons[expression] = value;

As others have pointed out, you can't do that with literal object notation. 正如其他人所指出的那样,你不能用文字对象表示法来做到这一点。

But, I think using the title as a key is a less natural representation compared with putting the buttons in an array: 但是,与将按钮放在数组中相比,我认为使用标题作为键是不太自然的表示:

function see_menu_custom(t1, m1, t2, m2, t3, m3, t4, m4, t5, m5)
{   
    $(document).simpledialog2(
    { 
        mode: 'button',
        ...
        buttons :
        [
            {
                label: 'My arbitrary string value',
                click: function () { 
                    sendMessage(username, token, t1, m1);
                },
                ...
                theme : "e"
            },
        ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM