JavaScript two dimensional array to achieve the provinces and cities linkage menu
- 2020-03-30 02:54:19
- OfStack
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
//Initializes a two-dimensional array to store city list items
var cities=[
[" anqing "," hefei "," tongcheng "],
[" shijiazhuang "," baoding "," tangshan "],
[" zhengzhou "," luoyang "," kaifeng "]
];
//When a province is selected, the method to add a city is called
function provinceChanged(sel){
//Alert (" length of select "+sel.options. Length);
//Sel is just a select object
//Iterate through the options collection to find the selected options
for(var x=0;x<sel.options.length;x++)
{
var opt=sel.options[x];
if(opt.selected)
{
//Adds an option to the select for the selected city
addCityToSelect(x)
}
}
}
//Adds the city item under the selected province to the city select
function addCityToSelect(x){
//Find the corresponding city from the two-dimensional array
var city=cities[x-1];
var citySelect=document.getElementById("select_city");
//Set the options length under the city's select object to 1
citySelect.options.length=1;
//Set the length of the options collection and delete it
//citySelect.options.length=1;
for(var x=0;x<city.length;x++)
{
//Create the element node object
var optionName=document.createElement("option");
//Display the content for the option Settings
optionName.innerHTML=city[x];
//Adds the created option to the select
citySelect.appendChild(optionName);
}
}
</script>
</head>
<body>
<select onchange="provinceChanged(this);">
<!--this What is the meaning of this select The object provinceChanged(this), And in this method
The object itself is passed as a parameter so that it can be manipulated. -->
<option> Please select province </option>
<option> anhui </option>
<option> hebei </option>
<option> henan </option>
</select>
<select id="select_city">
<option> Please select city </option>
</select>
</body>
</html>