0

post lang 是根据用户的位置自动设置的,我想根据 post lang 将下拉菜单的值设置为语言。

这是我尝试使用但没有成功的代码:

 <label for="lang">Language</label>
 <select id="lang">
                    <? 
                        $_POST['lang'] = $lang;

                        switch ($lang) {
                        case "en":
                        $en = "selected";
                        break;
                        case "fr":
                        $fr ="selected";
                        break;
                    ?>                          

                    <option value="en" selected="<?$en?>">English</option>
                    <option value="fr" selected="<?$fr?>">Francais</option>
                    <option value="es" selected="<?$es?>">Español</option>
                    <option value="de" selected="<?$de?>">Deutsch</option>
                    <option value="chin_trad" selected="">Chinese Traditional</option>
                    <option value="chin_orig" selected="">Chinese Original</option>
                </select>
4

2 回答 2

0

我的偏好包括一些 JavaScript:

<select id="lang" data-default="<?=$lang?>">
    <option value="en">English</option>
    <option value="fr">Fran&ccedil;ais</option>
    <option value="es">Espa&ntilde;ol</option>
    ...
</select>

<script type="text/javascript">
    (function() {
        var sel = document.getElementsByTagName('select'), l = sel.length, i,
            def, opts, m, j;
        for( i=0; i<l; i++) {
            if( def = sel[i].getAttribute("data-default")) {
                opts = sel[i].options;
                m = opts.length;
                for( j=0; j<m; j++) {
                    if( opts[j].value == def) {
                        opts[j].selected = true;
                        break;
                    }
                }
                sels[i].removeAttribute("data-default");
            }
        }
    })();
</script>
于 2012-08-03T15:18:54.697 回答
0

我已经评论并修复了您的代码,它应该可以工作(未经测试!)

<label for="lang">Language</label>
<select id="lang">
<?php // Don't use the shorthand notation!

// $_POST['lang'] = $lang;
// You're overwriting $_POST['lang']... should be:
$lang = $_POST['lang'];

switch ($lang) {
case "en": $en = "selected"; break;
case "fr": $fr ="selected"; break;
}
?>

    <!-- <option value="en" selected="<?$en?>">English</option> -->
    <!--                              ^^^^^^^ see below for fixed line -->
    <option value="en" selected="<?php echo $en; ?>">English</option>

    <!-- same for other options, adjusting the lang code -->

</select>
于 2012-08-03T15:23:40.013 回答