【问题标题】:How to create n-level (multi-level, cascading) dependent dropdown (selects, options)?如何创建 n 级(多级、级联)依赖下拉列表(选择、选项)?
【发布时间】:2014-08-14 06:29:13
【问题描述】:

目的:寻找最简单、更灵活的方式创建级联下拉列表,使用工具jquery(javascript)、php、mysql;

如果您有其他更简单/灵活的选择,请分享。

【问题讨论】:

    标签: php jquery html mysql json


    【解决方案1】:

    HTML

    <select class="step1 step" name="step1"></select>
    <select class="step2 step" name="step2"></select>
    <select class="step3 step" name="step3"></select>
    <select class="step4 step" name="step4"></select>
    <select class="step5 step" name="step5"></select>
    

    出于信息目的,通常在最后一个下拉列表中被选中:

    <textarea id="info" disabled=""></textarea>
    

    JQUERY

    $.get(url, function(data){
        var options = function(data, level, selected) {
            $.each(data, function(i, item) {
                var pid = $('.step'+(level-1)).val();
    
                if(pid == item.pid || item.pid == 0) {
                    if(!$('.step').find('option[value='+item.id+']').length) {
                        $('.step'+level).append($('<option>', {
                            value: item.id,
                            text : item.name,
                            info: item.info,
                        }));
                    }
    
                    if(item.childs)
                        options(item.childs, level+1);
                }
            });
    
            var info = $('.step option:selected:last').attr('info');
            $('#info').val(info);
        }
        options(data, 1);
    
        $('.step').change(function() {
            var selected = $(this).val();
            $(this).nextAll('.step').empty();
    
            options(data, 1);
        });
    });
    

    JSON

    {"1":{"id":"1","name":"Category-1","info":"","pid":"0","childs":{"3":{"id":"3","name":"Category-1-2","info":"","pid":"1","childs":{"19":{"id":"19","name":"Captiva","info":"Some text","pid":"3"}}}}}}
    

    等等……

    PHP

    foreach ($info as $key => $value) {
        $info[$value->id] = $value;
        unset($info[0]);
    }
    
    foreach($info as $key => $val)
        $childs[$val->pid][$key] = $val;
    
    foreach($info as $item)
        if (isset($childs[$item->id]))
            $item->childs = $childs[$item->id];
    
    $total = count($info);
    foreach($info as $key => $val){
        if($info[$key]->pid != 0)
            unset($info[$key]);
    }
    

    MYSQL

    CREATE TABLE IF NOT EXISTS `dropdown_list` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `name` varchar(255) NOT NULL,
      `info` varchar(1000) NOT NULL,
      `pid` int(11) NOT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-25
      • 2016-08-13
      • 1970-01-01
      • 1970-01-01
      • 2016-04-05
      • 1970-01-01
      • 2018-04-07
      • 1970-01-01
      相关资源
      最近更新 更多