动态选择下拉菜单

我有3个选项菜单,在最简单的形式如下:动态选择下拉菜单

<form action="samePageAction" form="post"> 

<select>

<option>Yes</option>

<option>No</option>

<option>Maybe</option>

</select>

</form>

,它只是根据用户的数据库中设置这是不是真的“动态”,我选择什么“选项”默认显示:在每种情况下

<form action="samePageAction" form="post"> 

<select>

<?

if(!$personUndecided && $personHasAgreed){

?>

<option>Yes</option>

<option>No</option>

<option>Maybe</option>

<?

} else if(!$personUndecided && !$personHasAgreed){

?>

<option>No</option>

<option>Yes</option>

<option>Maybe</option>

</select>

<?

else {

?>

<option>Maybe</option>

<option>Yes</option>

<option>No</option>

</select>

<? } ?>

</form>

“第一”的选择是很重要的,因为当表单被禁用,这是用户将看到的选项。当我看到这件事情时,我感到非常痛苦,但更好的解决方案不会来到我身上。我怎样才能优化这个菜单?

问题:如何防止重复自己这么多。或者这段代码看起来完全正常吗?

回答:

您可以短代码以这种方式,即:

<?php 

if($personHasAgreed) $choices = array ('Yes', 'No', 'Maybe');

elseif(!$personHasAgreed) $choices = array ('No', 'Yes', 'Maybe');

else $choices = array ('Maybe','Yes', 'No');

foreach($choices as $choice):

?>

<option><?php echo $choice; ?></option>

<?php endforeach; ?>

这样,你先分配取决于$personHasAgreed设置的各种选择的值,然后执行一个foreach环路输出的每个选项。

编辑:请注意,我认为else语句将永远不会被执行...

回答:

explode功能简单的解决方案:

<form action="samePageAction" form="post"> 

<select>

<?php

$personHasAgreed = "";

$valueString = ($personHasAgreed === 1)? "Yes,No,Maybe" : (($personHasAgreed === 0)? "No,Yes,Maybe" : "Maybe,Yes,No");

$valueString = explode(",", $valueString);

foreach($valueString as $word){

echo "<option>". $word ."<option>";

}

?>

</select>

</form>

回答:

像这样的事情?

<form action="samePageAction" method="post"> 

<select>

<?php

$possAnswer = array(

"1" => "<option>Yes</option>",

"0" => "<option>No</option>",

"2" => "<option>Maybe</option>"

);

if($personHasAgreed) {

echo $possAnswer[1] . $possAnswer[0] . $possAnswer[2];

} else if(!$personHasAgreed){

echo $possAnswer[0] . $possAnswer[1] . $possAnswer[2];

} else {

echo $possAnswer[2] . $possAnswer[1] . $possAnswer[0];

}

?>

</select>

</form>

`

以上是 动态选择下拉菜单 的全部内容, 来源链接: utcz.com/qa/258376.html

回到顶部