2011-02-04 55 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>