代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="js/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<style type="text/css">
select{
width: 150px;
}
</style>
</head>
<body>
<select name="firstEn" id="firstEn">
</select>
<select name="secondEn" id="secondEn">
</select>
<script type="text/javascript">
let data = [
{
firstData:'农用动力机械',
secondData:['内燃机和装备内燃机的拖拉机','电动机','风力机','水轮机和各种小型发电机组']
},
{
firstData:'农用建设机械',
secondData:['推土机','平地机','铲运机','挖掘机','装载机','凿岩机']
},
{
firstData:'农用耕作机械',
secondData:['桦式犁','圆盘犁','凿式犁','旋耕机']
},
{
firstData:'农用种植机械',
secondData:['播种机','栽种机','秧苗栽植机']
},
{
firstData:'农用保护机械',
secondData:['化学或物理方法除草设备','用物理方法防治病虫害的设备']
},
{
firstData:'农田排灌机械',
secondData:['水泵','喷灌设备']
},
{
firstData:'谷物联合收获机',
secondData:['谷物联合收获机','棉花收获机']
},
{
firstData:'农产品加工机械',
secondData:['碾米机','磨粉机']
}
]
//第一个下拉列表的默认
let oneSelect = 2;
//给两个下拉列表赋值
setSelectFn(data,'firstEn',true);
setSelectFn(data[oneSelect].secondData,'secondEn',false);
//更改第一个下拉列表
$('#firstEn').change(function(){
let index = $(this).find('option:selected').attr('key');
setSelectFn(data[index].secondData,'secondEn',false);
})
//更改第二个下拉列表
$('#secondEn').change(function(){
console.log($('#firstEn option:selected').val())
console.log($('#secondEn option:selected').val())
})
//设置下拉列表的默认选项
$("#firstEn option[key="+oneSelect+"]").prop("selected",true);
$("#secondEn option[value='圆盘犁']").prop("selected",true);
//填写option选项
function setSelectFn(array,idName,isFirst){
let html = '';
array.forEach((v,k)=>{
let value;
if(isFirst){
value = v.firstData;
}else{
value = v;
}
html += `<option key="${k}" value="${value}">${value}</option>`;
console.log()
})
$('#'+idName).html(html);
}
</script>
</body>
</html>
运行结果: