post lang是根据用户的位置自动设置的,我想根据帖子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>
答案 0 :(得分:0)
我的偏好包括一些JavaScript:
<select id="lang" data-default="<?=$lang?>">
<option value="en">English</option>
<option value="fr">Français</option>
<option value="es">Españ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>
答案 1 :(得分: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>