0

在用户点击提交按钮后保留下拉选择 我只是在第 1-4 天工作

<?PHP
    $day = array( );
    $day[0] = "1";
    $day[1] = "2";
    $day[2] = "3";
    $day[3] = "4";
    $days=$day;   
?>

<select name="day"> 
     <option value="day">Day</option>
     <?PHP
        for ($days = 0; $days < 4; $days++) {           
            print"<option value='$day[$days]'>$day[$days]</option>";
        }
    ?>
</select>
4

3 回答 3

0

对于初学者,该代码需要认真重新思考。

您首先创建一个数组,然后无缘无故地将其添加到不同的变量中。

其次,您的值与索引仅相差一个数字,您可以轻松地即时计算。

最后,您在同一个数组中循环以仅使用索引(不需要数组)。

所以,把一些代码放在我的嘴里,它看起来像:

<select name="day"> 
    <option value="day">Day</option>
    <?php
        for ($day = 1; $day <= 4; $day++) {
            print"<option value='$day'>$day</option>";
        }
    ?>
</select>

也就是说,您从未提到需要选择哪个项目。假设它是一个名为 的变量$the_day,这里还有一些代码:

<?php

$the_day = 4;

?><select name="day"> 
    <option value="day">Day</option>
    <?php
        for ($day = 1; $day <= 4; $day++) {
            $it_is = $day == $the_day ? 'selected="selected"' : '';
            print"<option value='$day' $it_is>$day</option>";
        }
    ?>
</select>
于 2012-08-08T13:18:22.817 回答
0

您可以在语句中使用选定的关键字

print"<option value='$day[$days]' selected='selected'>$day[$days]</option>";
于 2012-08-08T13:19:41.050 回答
0

You can pull the value passed in out of the $_REQUEST superglobal and check for it on each iteration. The <option> tag that you want preselected should include the selected attribute. Also, there is no need to create an array of consecutive integers when you can simply increment a counter in a loop. Something like this should work for you:

<select name="day"> 
<option value="day">Day</option>
<?php
    $day = null;
    if (array_key_exists('day', $_REQUEST) {
        $day = $_REQUEST['day'];
    }
    for ($i = 1; $i <= 4; $i++) {
       echo '<option value="' . $i . '"';
       if ($i == $day) {
           echo ' selected="selected"';
       }
       echo '>' . $i . "</option>\n";
    }
?>
</select>
于 2012-08-08T13:19:56.047 回答