2011-02-04 26 views
1

語言我有我的網站上的下拉菜單,我想用不同的語言之間切換:我怎樣才能得到上面的菜單中顯示的語言是創建菜單切換現場

<select onChange="if(this.selectedIndex!=0) self.location=this.options[this.selectedIndex].value" name="userLanguage" id="userLanguage"> 
    <option value="http://demo.com/?lang=en"> 
       English (International)</option>  
     <option value="http://demo.com/?lang=es"> 
       Español (European)</option> 
        </select> 

目前顯示。有沒有表現出積極的狀態。網站正在使用PHP。

在此先感謝。

回答

2

使用PHP這是一展身手。 (我改變了選擇了一下。)

<select onChange="if(this.selectedIndex!=0) self.location='http://demo.com/?lang='+this.options[this.selectedIndex].value" name="userLanguage" id="userLanguage"> 
    <option <?php if ($_GET['lang'] == "en") { ?>selected="selected"<?php } ?> value="en">English (International)</option>  
    <option <?php if ($_GET['lang'] == "es") { ?>selected="selected"<?php } ?> value="es">Español (European)</option> 
</select> 

希望這會有所幫助!

+0

+1如果它是窗體中唯一的字段,您也可以將選擇的名稱更改爲`lang`並提交它。 – jeroen 2011-02-04 17:06:02

0

如果您使用的是PHP,我會建議你refector這樣的代碼,因爲這樣你可以輕鬆地添加新的語言,無需編寫HTML代碼或額外的JavaScript。您可以使用$ langs數組來保存當前的一組語言。

我也做了$ server_location包含當前頁面URL的變量。這樣,當您將頁面移動到不同的服務器和域時,或者如果您重命名頁面,您就不會遇到問題。

<? 
     $langs = array('en' => 'English (International)', 
         'es' => 'Español (European)' 
        ); 

     function is_current_language($code) 
     { 
       return ($code == $_GET['lang'])? 'selected="selected"': ""; 
     } 

     $server_location= $_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME']; 

    ?> 

    <select onchange="if(this.selectedIndex!=0) self.location='<?=$server_location;?>?lang='+this.options[this.selectedIndex].value" name="userLanguage" id="userLanguage"> 

     <? foreach($langs as $code => $lang): ?> 
      <option <?= is_current_language($code); ?> value="<?= $code; ?>"> 
      <?= $lang; ?> 
      </option> 
     <? endforeach; ?> 

    </select>