Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/242.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何动态生成下拉菜单_Javascript_Php - Fatal编程技术网

Javascript 如何动态生成下拉菜单

Javascript 如何动态生成下拉菜单,javascript,php,Javascript,Php,在我的php中,我创建了两个下拉列表或选择列表。我的下拉列表如下: ... 水果 蔬菜 -- 苹果 生菜 橙色 西红柿 胡萝卜 芒果 您应该在JavaScript对象中指定所有水果和蔬菜内容,并在另一个下拉列表中显示食品值的相关内容,请参见下面的演示 Food: <select name="food" id="food"> <option value="">...</option> <option value="Fruits">

在我的php中,我创建了两个下拉列表或选择列表。我的下拉列表如下:


...
水果
蔬菜
--
苹果
生菜
橙色
西红柿
胡萝卜
芒果

您应该在
JavaScript
对象中指定所有
水果
蔬菜
内容,并在另一个下拉列表中显示
食品
值的相关内容,请参见下面的演示

Food: 
 <select name="food" id="food">
   <option value="">...</option>
   <option value="Fruits">Fruits</option>
   <option value="Vegetables">Vegetables</option>
 </select>
Content 
 <select name="contents" id="contents">
  <option value="">...</option>
 </select>

使用jQuery可以做到这一点,但在大型应用程序或网站中很快就会变得难以管理

如果您这样做,我将避免使用两个不同的选择框,因为这将迫使您为表单帖子选择两个不同的名称,除非您使用更多jQuery黑客来解决此问题

我的建议是看一个轻量级JS框架。有你需要的

var fructopts=[“苹果”、“橙子”、“芒果”];
var vegOpts=[“生菜”、“番茄”、“胡萝卜”];
美元(“#食品”)。变化(功能){
var val=$(this.val();
如果(val==“”){
返回;
}
$(“#type”).find('option')。not(':first')。remove().end();
$.each(val==“水果”?水果选项:蔬菜选项,函数(i,v){
$(“#type”).append(“+v+”);
});
$.each(val==“Fruits”?vegOpts:fruitOpts,function(i,v){
$(“#type”).append(“+v+”);
});
});

为此,您需要使用JQuery。
请参阅我的解决方案:

代码如下:

HTML

另一种选择

该列表分为两个数组:食物,对应于所选类型;与所选类型不对应。每个数组依次按名称排序:

HTML:


...
水果
蔬菜
浆果
--
苹果
生菜
西红柿
草莓的
JQuery:

函数selectFoodType()
{
var type=$('select#food option:selected').val();
var itemsId=document.getElementById(“类型”);
var items=itemsId.getElementsByTagName(“选项”);
选择的变量类型=[],其他类型=[];
所选_类型[0]=项目[0];
对于(变量i=1;i
它的版本适用于两个不同的php页面:

1.php

2.php



你用谷歌搜索过你的标题吗?可能是@SamP的副本,这和我要找的不完全一样。这些答案不是很具体,很好!但我想他还是想显示出于某种原因未选中的选项,只是在列表的底部。@SamP,我错过了,请看我更新的答案。这确实有效,您甚至还添加了更多值。但是,我想知道如何将其实现为两种不同的php表单?我的意思是,第一个下拉列表在一个php页面中,第二个下拉列表在我的第一个php.Ok之后的另一个页面中。我为两个不同的php页面添加了这个版本
var data = {
   'Fruits':['Apple', 'Lettuce', 'Orange', 'Mango'], 
   'Vegetables': ['Tomato', 'Carrots']
};

document.getElementById("food").onchange = function(Event){
    var contents = document.getElementById("contents");
    contents.innerHTML = "";
    for(var i in data[this.value]){
        var option = document.createElement("option");
        option.setAttribute('value',data[this.value][i]);
        option.text = data[this.value][i];
        contents.appendChild(option);
    }
    var expect_data = Event.target.value == "Fruits" ? "Vegetables" : "Fruits";
    for(var i in data[expect_data]){
        var option = document.createElement("option");
        option.setAttribute('value',data[expect_data][i]);
        option.text = data[expect_data][i];
        contents.appendChild(option);
    }
}
var fruitOpts = ["Apple", "Orange", "Mango"];
var vegOpts = ["Lettuce", "Tomato", "Carrots"];

$("#food").change(function () {
    var val = $(this).val();
    if (val === "") {
        return;
    }
    $("#type").find('option').not(':first').remove().end();

    $.each(val === "Fruits" ? fruitOpts : vegOpts, function (i, v) {
        $("#type").append("<option value=\"" + v + "\">" + v + "</option>");
    });

    $.each(val === "Fruits" ? vegOpts : fruitOpts, function (i, v) {
        $("#type").append("<option value=\"" + v + "\">" + v + "</option>");
    });
});
<select name="food" >
<option value="">...</option>
<option value="Fruits">Fruits</option>
<option value="Vegetables">Vegetables</option>
</select>

<select name='type' >
    <option>-- Select Food Type --</option>
</select>

<select id='Fruits' style='display:none' >
<option value="">--</option>
<option value="Apple">Apple</option>
<option value="Orange">Orange</option>
<option value="Mango">Mango</option>
</select>

<select id='Vegetables' style='display:none' >
<option value="">--</option>
<option value="Lettuce">Lettuce</option>
<option value="Tomato">Tomato</option>
<option value="Carrots">Carrots</option>
</select>
$(document).ready(function(){
    $("select[name='food']").on("change", function(){
              var value = $(this).val();
              $("select[name='type']").html($("#" + value).html());
      });
});
<select id="food" name="food" onchange="selectFoodType()">
    <option value="">...</option>
    <option value="Fruits">Fruits</option>
    <option value="Vegetables">Vegetables</option>
    <option value="Berries">Berries</option>
</select>
<select id='type' name="type">
    <option value="">--</option>
    <option data-type='Fruits' value="Apple">Apple</option>
    <option data-type='Vegetables' value="Lettuce">Lettuce</option>
    <option data-type='Vegetables' value="Tomato">Tomato</option>
    <option data-type='Berries' value="Strawberry">Strawberry</option>
</select>
function selectFoodType()
{
    var type = $('select#food option:selected').val();
    var itemsId = document.getElementById("type");
    var items = itemsId.getElementsByTagName("option");
    var selected_type = [], other_types = [];
    selected_type[0] = items[0];
    for (var i = 1; i < items.length; i++){
        if ($(items[i]).data('type') === type) {
            selected_type.push(items[i]);
            continue;
        }
        other_types.push(items[i]);
    }
    selected_type = selected_type.sort(sortByName);
    other_types = other_types.sort(sortByName);
    $.merge(selected_type, other_types);
    var list = '';
    for (i=0; i<selected_type.length; i++) {
        list += selected_type[i].outerHTML;
    }
    $(items).remove();
    $(itemsId).append(list);
}

function sortByName(a, b) {
    if (a.text > b.text) return 1;
    else if (a.text < b.text) return -1;
    return 0;
}
<script src="1.js"></script>
<a id='link' href='2.php'>go to another page</a>
<select id="food" name="food" onchange="selectFoodType()">
    <option value="">...</option>
    <option value="Fruits">Fruits</option>
    <option value="Vegetables">Vegetables</option>
    <option value="Berries">Berries</option>
</select>
function selectFoodType()
{
    var link = $('#link');
    var type = $('select#food option:selected').val();
    link.attr('href', link.attr('href') + '?type=' + type);
}
<script src="2.js"></script>
<select id='type' name="type" data-type='<?=$_GET['type']?>'>
    <option value="">--</option>
    <option data-type='Fruits' value="Apple">Apple</option>
    <option data-type='Vegetables' value="Tomato">Tomato</option>
    <option data-type='Vegetables' value="Carrots">Carrots</option>
    <option data-type='Berries' value="Strawberry">Strawberry</option>
</select>
$(function() {
    var type = $('select#type').data('type');
    var itemsId = document.getElementById("type");
    var items = itemsId.getElementsByTagName("option");
    var selected_type = [], other_types = [];
    selected_type[0] = items[0];
    for (var i = 1; i < items.length; i++){
        if ($(items[i]).data('type') === type) {
            selected_type.push(items[i]);
            continue;
        }
        other_types.push(items[i]);
    }
    selected_type = selected_type.sort(sortByName);
    other_types = other_types.sort(sortByName);
    $.merge(selected_type, other_types);
    var list = '';
    for (i=0; i<selected_type.length; i++) {
        list += selected_type[i].outerHTML;
    }
    $(items).remove();
    $(itemsId).append(list);
});

function sortByName(a, b) {
    if (a.text > b.text) return 1;
    else if (a.text < b.text) return -1;
    return 0;
}