gpt4 book ai didi

php - 如何创建n级(多级、级联)依赖下拉列表(选择、选项)?

转载 作者:行者123 更新时间:2023-11-29 23:56:27 24 4
gpt4 key购买 nike

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

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

最佳答案

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 ;

关于php - 如何创建n级(多级、级联)依赖下拉列表(选择、选项)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25301429/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com