0

我希望有人可以帮助我朝着正确的方向前进。我目前有一个文件,我将其命名为 data.php。在这个文件中,我有以下数据:

$sports_arr = array();
$sports_arr[] = "Basketball";
$sports_arr[] = "Baseball";
$sports_arr[] = "Football";

我在同一个 data.php 文件中也有以下数组:

$position = array();
$position['Basketball'][] = "Power Forward";
$position['Basketball'][] = "Small Forward";
$position['Basketball'][] = "Center";
$position['Soccer'][] = "Center Forward";
$position['Soccer'][] = "Right Wing";
$position['Soccer'][] = "Left Wing";
$position['Football'][] = "Halfback";
$position['Football'][] = "Fullback";
$position['Football'][] = "Wide Reciever";
$position['Football'][] = "Tight End";
$position['Football'][] = "Center";

问题是我试图弄清楚如何拥有第一个下拉列表,目前正在填充以下代码:

<div class="selectStyled">
    <select name="Sport1" class="styled">
    <option id="default" value="">Your Sport</option>
        <?php natsort($sports_arr);
        foreach ($sports_arr as $key => $val) { 
            echo "<option value='" . $val . "' id='position" . $key . "'>" . $val . "</option>";
        } ?>
    </select>
</div>

这是我遇到问题的地方。我想要的是基于上面下拉列表的结果(例如用户选择棒球),我想要第二个后续下拉列表以填充正确的位置数组。因此,如果他们选择篮球,它将立即动态地填充页面上的第二个下拉列表,其中包含篮球位置。如果他们改变主意并选择足球,它将在第二个下拉列表中动态填充足球位置。

任何帮助在这里表示赞赏。我遇到了一个主要的路障......谢谢!

4

2 回答 2

2

请试试:

<?php
$sports_arr = array();
$sports_arr[] = "Basketball";
$sports_arr[] = "Baseball";
$sports_arr[] = "Football";

$position = array();
$position['Basketball'][] = "Power Forward";
$position['Basketball'][] = "Small Forward";
$position['Basketball'][] = "Center";
$position['Soccer'][] = "Center Forward";
$position['Soccer'][] = "Right Wing";
$position['Soccer'][] = "Left Wing";
$position['Football'][] = "Halfback";
$position['Football'][] = "Fullback";
$position['Football'][] = "Wide Reciever";
$position['Football'][] = "Tight End";
$position['Football'][] = "Center";
?>

<div class="home">
    <select id="s1">
        <?php foreach($sports_arr as $sa) { ?>
        <option value="<?php echo $sa; ?>"><?php echo $sa; ?></option>
        <?php } ?>
    </select>
    <select id="s2">
    </select>
</div>

<script type="text/javascript">
var s1= document.getElementById("s1");
var s2 = document.getElementById("s2");
onchange(); //Change options after page load
s1.onchange = onchange; // change options when s1 is changed

function onchange() {
    <?php foreach ($sports_arr as $sa) {?>
        if (s1.value == '<?php echo $sa; ?>') {
            option_html = "";
            <?php if (isset($position[$sa])) { ?> // Make sure position is exist
                <?php foreach ($position[$sa] as $value) { ?>
                    option_html += "<option><?php echo $value; ?></option>";
                <?php } ?>
            <?php } ?>
            s2.innerHTML = option_html;
        }
    <?php } ?>
}
</script>

大多数时候,人们使用 ajax,但如果你的网络很慢,ajax 就不是好方法。

于 2013-04-10T05:32:56.663 回答
0

如果用户从第一个下拉列表中选择篮球,您希望,篮球阵列的所有记录显示在第二个下拉列表中。

所以你应该在第一个下拉列表的 onChange() 事件上使用 AJAX 函数。

于 2013-04-10T04:51:45.067 回答