纯js实现二级联动代码

2024年07月25日 建站教程

1、html代码

<select onchange="gradeChange()" id="first">
<option disabled="" selected="" value="">请选择大类</option>
</select>
<select id="second">
<option disabled="" selected="" value="">请选选择小类</option>
</select>

js代码

var firstData = ["家电", "图书", "医药"];
var firstIds = ["123", "124", "125"];
var secondData = [
    ["电风扇", "电表箱", "洗衣机"],
    ["科幻小说", "雨果奖入选"],
    ["感冒", "减肥", "骨折"]
];
var data_arr_2id = [
    ["A", "B", "C"],
    ["D", "E", "F"],
    ["G", "H", "I"]
];

function gradeChange() {
    var objS = document.getElementById("first");
    var index = objS.selectedIndex; // 选中索引
    var id = index - 1;
    setSecond(id);
}

function setFirst() {
    //alert(id);
    var first = document.getElementById("first");
    var data_arr = firstData;
    var id_arr = firstIds;
    var select_html = "<option disabled selected value=\"\">请选择大类</option>";
    for (var i = 0; i < id_arr.length; i++) {
        var _data = data_arr[i];
        var _id = id_arr[i];
        select_html += "<option value=\"" + _id + "\">" + _data + "</option>";
    }
    first.innerHTML = select_html;
}
 
function setSecond(id) {
    //alert(id);
    var second = document.getElementById("second");
    var data_arr = secondData[id];
    var id_arr = data_arr_2id[id];
    var select2_html = "";
    for (var i = 0; i < id_arr.length; i++) {
        var _data = data_arr[i];
        var _id = id_arr[i];
        select2_html += "<option value=\"" + _id + "\">" + _data + "</option>";
    }
    second.innerHTML = select2_html;
}

setFirst();

本文链接:http://so.lmcjl.com/news/9155/

展开阅读全文
相关内容