[英]How to set a property value based on a variable in Javascript
問題是我有這段代碼(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”,而不是其內容。 所以,問題是,我該怎么辦?
嘗試這個。
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
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
});
您不能內聯進行此操作。 您必須先聲明該對象,然后使用方括號成員運算符設置屬性:
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
});
試試看,未經測試:
$("#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");
}
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.