一开始遇到这种二级联动的写法,都是望而却步,今天性质大发,简单的写一篇代码,总结一下,与大家共勉:
一句话说明问题:点击select后,用selectedIndex获取该select选中的索引[index],然后点击第二个select的时候,以该索引去筛选该索引对应的值
看了后是不是感觉很简单,下面我列举一下例子中用到的知识点:
请求json数据,用到ajax,为了方面,这里引用JQ监听select的value值的变化用到的是change() 函数一些select的知识: var obj = document.getElementByIdx_x(”testSelect”); // 定位 id var index = obj.selectedIndex; // 选中索引 var text = obj.options[index].text; // 选中文本 var value = obj.options[index].value; // 选中值 jQuery 中获得选中 select 值 第一种方式 $('#testSelect option:selected').text(); // 选中的文本 $('#testSelect option:selected') .val();// 选中的值 $("#testSelect").get(0).selectedIndex;// 索引 第二种方式 $("#tesetSelect").find("option:selected").text(); …….val(); …….get(0).selectedIndex;下面我直接粘贴上项目代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <script src="../js/jquery-2.1.1.min.js"></script> </head> <body> <div> 选择城市: <select id="city" onchange="changeSelect(this.selectedIndex)"> </select> </div> <div> 选择学校: <select id="school"> </select> </div> <script> $.ajax({ //请求方式为get type: "GET", //json文件位置 url: "../school.json", //返回数据格式为json dataType: "json", //请求成功完成后要执行的方法 success: function (data) { // console.log(data); var temp; for (var item in data) { temp += "<option id = " + data[item].id + " >" + data[item].name + "</option>"; console.log(data[item].id + '--------' + data[item].name + '----------------省份'); var arr_province = data[item].name; var a = data[item].school; for (let i in a) { console.log(a[i].name); } }; $("#city").append(temp); } }) var index = $("#city").get(0).selectedIndex; function changeSelect(index) { console.log(index); $.ajax({ //请求方式为get type: "GET", //json文件位置 url: "../school.json", //返回数据格式为json dataType: "json", //请求成功完成后要执行的方法 success: function (data) { console.log(data); console.log(data[index].id + '--------' + data[index].name); var a = data[index].school; var tpl; for (var i in a) { console.log(a[i].name); tpl += "<option>" + a[i].name + "</option>"; } $("#school").append(tpl); } }) } </script> </body> </html>