Home > Article > Web Front-end > Simple implementation of three-level linkage using JavaScript
In actual JavaScript project development, we often need three-level linkage, such as the selection of provinces and municipalities, the selection of three-level classification of goods, etc. Today we will explain how JavaScript implements three-level linkage, and we will share the JavaScript source code with you! If you are not familiar with JavaScript to implement three-level linkage, you can take a look with us!
Knowledge points:
1. json.parse() converts the json format string into Object. json.stringify() converts the object into a json format string.
2. Important attribute selectedIndex: Returns the index number of the selected option in the drop-down list.
3. onchangeEvent
The following is the code:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>三级联动</title> </head> <body> <select id="province"> <!-- <option>北京</option> <option>天津</option> --> </select> <select id="city"></select> <select id="count"></select> <script type="text/javascript" src="china.js"></script> <script type="text/javascript"> var province = document.getElementById("province"); var city = document.getElementById("city"); var count = document.getElementById("count"); var chinaArea = JSON.parse(chinaArea);//将字符串格式的json数据转换成对象 // var chinaArea = eval("("+chinaArea+")"); // var chinaArea = new Function("return " + chinaArea)(); //1.遍历省份 var provinceList = chinaArea.china.province;//数组 for(var i = 0 ; i < provinceList.length; i++) { var option = document.createElement("option"); option.innerHTML = provinceList[i]["-name"]; province.appendChild(option); } province.onchange = function() { //选择省份之后,市区跟着变化 cityData(); countData(); } cityData(); //市区的数据填充 var sIndex = 0; var cityIndex = 0; function cityData() { //清除原来的市区信息 city.innerHTML = ""; //2.遍历市区 sIndex = province.selectedIndex;//设置或返回下拉列表备选选项的索引号。 for(var j = 0; j < provinceList[sIndex].city.length;j++) { var option = document.createElement("option"); option.innerHTML = provinceList[sIndex].city[j]["-name"]; city.appendChild(option); } } //县区数据填充 function countData() { //清除原来的县区信息 count.innerHTML = ""; // cityIndex = city.selectedIndex; var countList = chinaArea.china.province[sIndex].city[cityIndex].county; for(var k = 0; k < countList.length; k++) { var option = document.createElement("option"); option.innerHTML = countList[k]["-name"]; count.appendChild(option); } } city.onchange = function() { countData(); } countData(); </script> </body> </html>
You can combine the source code and Check out the knowledge! Try to write it yourself and strengthen your knowledge!
Related recommendations:
js realizes the sharing of three-level linkage plug-ins in provinces and municipalities
jQuery three-level linkage effect implementation method
The above is the detailed content of Simple implementation of three-level linkage using JavaScript. For more information, please follow other related articles on the PHP Chinese website!