Copy Code code as follows:
<! DOCTYPE html>
<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 invoked
function provincechanged (SEL) {
Alert ("Length of select" +sel.options.length);
The SEL is actually a select object
Traverse the options collection to find the selected option
for (Var x=0;x<sel.options.length;x++)
{
var opt=sel.options[x];
if (opt.selected)
{
Add option to selected city's Select
Addcitytoselect (x)
}
}
}
Add the city items in the selected province to the Select
function Addcitytoselect (x) {
Find the corresponding city from the two-dimensional array
var city=cities[x-1];
var Cityselect=document.getelementbyid ("Select_city");
/*================== deletes an element that already exists in the node ===============
When a second or nth call to a method has been added to the city select object, the node has been added before, so there is a purge.
Thinking 1:select the object's RemoveChild (), so you can delete the byte point by looping through the loop.
Idea 2: Directly set Select.options.length=1 can achieve the same effect.
*/
Set the options length under the city's Select object to 1
cityselect.options.length=1;
Sets the length of the options collection, deleting
cityselect.options.length=1;
for (Var x=0;x<city.length;x++)
{
Creating an Element Node object
var optionname=document.createelement ("option");
Set the display for option
OPTIONNAME.INNERHTML=CITY[X];
Add the option you created to the Select
Cityselect.appendchild (Optionname);
/*
In this place, after adding all the cities below a certain province to the Cityselect object
When the second province is selected, all cities below the second province are appended to
Below the Cityselect node. The effect is wrong. So before each addition, ask to
Empty the contents below the Cityselect node. Next look:
================== deletes an element that already exists in the node ===============
*/
}
}
</script>
<body>
<select onchange= "provincechanged (this);" >
<!--This means that the Select object calls Provincechanged (this), and in this method
The object itself is passed as a parameter to manipulate it. -->
<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>