2011-08-18 130 views
1

属性值的问题是我有这样一段代码(jQuery用户界面):如何设置基于变量在Javascript

$("#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”,而不是它的内容。所以,问题是,我能做什么?

+0

嘛,我不是很熟悉jQuery UI的,但尝试:'按钮[STR_REMOVE] =功能(){$(this).dialog(“关闭”);}'可能会帮助。 – J0HN

+0

对象属性不能用对象字面值以变量方式定义。 J0HN的解决方案将有所帮助。顺便说一句,jQuery UI与此无关。这是一个关于Javascript对象定义的问题,其他所有内容都应该从问题中删除。 –

回答

3

试试这个。

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

+0

+1:谢谢你。修正了一些小错别字。希望它确定 – naveen

+0

@naveen:当然,很难在SO回答字段中输入代码;-) – Fender

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

你不能做到这一点在线。你必须首先声明的对象,然后使用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 
}); 
+0

+1:...是的,现在它很丑。 –

+0

你可以做到这一点。看到挡泥板回答 – naveen

+0

@naveen足够公平 - 有一个jQuery UI解决方案。尽管如此,我已经展示了使用对象文字来完成OP想要的唯一方法。 – lonesomeday

0

试试这个,没有测试:

$("#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"); 
     } 
    } 
});