2012-03-07 191 views
2

我有一個平凡的jQuery的對話是這樣的:更改我的jQuery的對話框按鈕文本時,對話框負載

<div id="dialog-confirm" title="Empty the recycle bin?"> 
    <p>These items will be permanently deleted and cannot be recovered. Are you sure?</p> 
</div> 

<script> 
    $(function(){ 
     $('#dialog-confirm').dialog({ 
      resizable: false, 
      height: 140, 
      modal: true, 
      buttons: 
       { 
        "Delete all items": function() { $(this).dialog('close'); }, 
        "Cancel": function() { $(this).dialog('close'); } 
       } 
     }); 
    }) 
</script> 

有時候,我需要改變文本按鈕(如果用戶的語言是法語爲例)。在這種情況下,當jquery對話框加載時,我想調整按鈕。可能嗎?

謝謝

+1

是的,這是可能的。 – j08691 2012-03-07 20:07:30

+1

你使用任何類型的服務器端語言(PHP,ASP等)?如果是這樣,你可以根據任何正在檢測語言 – 2012-03-07 20:04:54

+0

生成按鈕名稱,我使用ASP.NET MVC。我可以輕鬆檢測到語言(這不是我的問題),但我怎樣才能調整按鈕文字?如何在對話框加載中用「Supprimer tous leséléments」替換「刪除所有項目」? – Bronzato 2012-03-07 20:07:52

回答

1

嗯,我認爲有兩種解決方案。

1.如果您將此代碼包含在您的html文件中,並且正在使用php或rails或asp進行解析,並且服務器碰巧知道頁面的語言,則可以將一個變量或項目只更換內部對話()在PHP

代碼它會像

[...]$(this).dialog('<?= $close_in_user_language ?>')[...] 

,但如果你不知道在服務器端,用戶語言或者你不解析與那塊文件的代碼我會建議創建一個全局的JavaScript變量(或更好的一個哈希表),當頁面加載任何你想要的東西時,這些變量會被填滿呃語言。事情是這樣的

這些項目將被永久刪除,無法恢復。你確定?

<script> 
    /* This code would have to be at the begining of your page with something 
    that sets the variables correctly acording to the user language. 
    In this case I'm using spanish for demonstration porpuses*/ 

    var close_in_user_language="cerrar" 
    var translation_table={"close":"cerrar"}; 

/* With this implementation you can also change the language on the fly */ 

    $(function(){ 
    $('#dialog-confirm').dialog({ 
     resizable: false, 
     height: 140, 
     modal: true, 
     buttons: 
      { 
       "Delete all items": function() { $(this).dialog(close_in_user_language); }, 
       "Cancel": function() { $(this).dialog(translation_table["close"]); } 
      } 
    }); 
}) 
</script> 

個人而言,我會建議你把寫在JSON你的服務器,只是會被分配到哈希表

3

動態的按鈕文本的翻譯做這樣的翻譯文件: -

dynamicBtnHandler("Supprimer tous les éléments", "Cancel"); 

function dynamicBtnHandler(btn1, btn2) 
{ 
    var btnNames = {}; 
    btnNames[btn1] = function(){ $(this).dialog('close'); }; 
    btnNames[btn2] = function(){ $(this).dialog('close'); }; 
    $(function(){ 

     $('#dialog-confirm').dialog({ 
      resizable: false, 
      height: 140, 
      modal: true, 
      buttons: btnNames 
     }); 
    }) 
} 

請參閱我的LIVE DEMO

+1

這應該是公認的答案 – AbdelHady 2015-11-05 12:17:15

0

這是一個簡單的例子。基本上,您可以使用對話框對象的選項方法在任何點更改按鈕。

jsFiddle example

jQuery的

$(".selector").dialog({ 
    autoOpen: true, 
    buttons: [ 
     { 
     text: "Ok", 
     click: function() { 
      $(this).dialog("close"); 
     }} 
    ] 
}); 
$('button').click(function() { 
    $('.selector').dialog("option", "buttons", [ 
     { 
     text: "Changed!", 
     click: function() { 
      $(this).dialog("close"); 
     }} 
    ]); 
});​ 

HTML

<div class="selector">Hello world</div> 
<button>Change text</button>​ 
相關問題