因为我有这样的数据库
id - id_parent - name
1 - 0 - root
2 - 1 - child_1
3 - 1 - child_2
4 - 3 - child_31
5 - 3 - child_32
6 - 2 - child_21
我必须创建一个选择,“onselect”显示带子项的新选择
然后首先从db中选择
<select>
<option>empty</option>
<option>root</option>
</select>
在root选择时,底部的新选择是
<select>
<option>child_1</option>
<option>child_2</option>
<select>
我正试图用jquery做到这一点......
答案 0 :(得分:0)
看到这个代码我解决了你的问题,我认为这将有助于你做这项工作
https://plnkr.co/edit/ckEIglujjD9OIOqeT6l5?p=preview
<h1>Hello Plunker!</h1>
<select id="parent">
<option value="0">empty</option>
<option value="1">root</option>
</select>
<select id="child">
</select>
<script>
$(document).ready(function() {
var info = [{
id: 1,
parent: 0,
name: 'root'
}, {
id: 2,
parent: 1,
name: 'child_1'
}, {
id: 3,
parent: 1,
name: 'child_2'
}, {
id: 4,
parent: 3,
name: 'child_31'
}, {
id: 5,
parent: 3,
name: 'child_32'
}, {
id: 6,
parent: 2,
name: 'child_21'
}
];
$("#parent").on('click', function() {
var nowValue = $(this).val();
$("#child").html("");
$.each(info, function(index, value) {
if (value.parent == nowValue) {
var option = $('<option/>');
option.attr({
'value': value.id
}).text(value.name);
$('#child').append(option);
}
});
});
});
</script>