2011-08-18 63 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"); 
     } 
    } 
});