二级联动下拉列表菜单的难点在于对后台返回的数据进行解析,不多逼逼,直接上代码

原生js实现二级联动下拉列表菜单-LMLPHP

上图是后台返回的数据

实现代码如下:

var deviceNotExist = true;//防止数据重复

if(data.code == 0) { //查询成功
var param = data.content;
for(i = 0; i < param.length; i++) {
deviceNotExist = true;
var detTim = [];
for(j in dev) {
if(param[i].sbbh == dev[j].sbbh) {
deviceNotExist = false;
var period = {
kssj: param[i].kssj,
jssj: param[i].jssj
}
tim[j].push(period);
break;
}
}
if(deviceNotExist) {
var deviceInfo = {
sbbh: param[i].sbbh,
sbmc: param[i].sbmc
}
dev.push(deviceInfo);
var period = {
kssj: param[i].kssj,
jssj: param[i].jssj
}
detTim.push(period);
tim.push(detTim);
}
}
mulArr.push(dev);
mulArr.push(tim);
for(var i = 0; i < mulArr[0].length; i++) {
$("#device").append("<option value=" + mulArr[0][i].sbbh + ">" + mulArr[0][i].sbmc + "</option>");
}
for(var i = 0; i < mulArr[1][0].length; i++) {
$("#period").append("<option value=startTime=" + mulArr[1][0][i].kssj + "&endTime=" + mulArr[1][0][i].jssj + ">" + mulArr[1][0][i].kssj + "-" + mulArr[1][0][i].jssj + "</option>");
}

//选择下拉框列表内容时下面的列表实现联动
$("#device").change(function() {
$("#period").html("");//改变列表值时先清空下面列表的内容
var dIndex = $("#device option:selected").index();//获取当前选中列表的下标
for(var i = 0; i < mulArr[1][dIndex].length; i++) {
$("#period").append("<option value=startTime=" + mulArr[1][dIndex][i].kssj + "&endTime=" + mulArr[1][dIndex][i].jssj + ">" + mulArr[1][dIndex][i].kssj + "-" + mulArr[1][dIndex][i].jssj + "</option>");
}
})

05-11 02:44