/*
1.select元素的option创建方式:【var option = new Option(‘想要显示的内容’);】
2.select元素中添加option方式:【select.options.add(新创建的option);】
3.select元素清空所有的option方式:【select.options.length = 0;】
4.select元素改变时触发的事件:【select.onchange = function(){};】
5.select元素当前正在选中的option的序号:【select.selectedIndex】,从0开始。
*/
//1.获取页面元素
var shengSelect = document.querySelector('.shengSelect');
var shiSelect = document.querySelector('.shiSelect');
var xianSelect = document.querySelector('.xianSelect');
//2.填充省的数据
//2.1准备数据
//省的数据
var shengArr = ['山东', '河北', '辽宁'];//1 0 2 0
//市的数据
var shiArr = [['临沂', '菏泽'], ['秦皇岛', '石家庄'], ['大连', '沈阳']];
var xianArr = [[['临1', '临2','临3'], ['菏1', '菏2']], [['秦1', '秦2'], ['石1', '石2']], [['大1', '大2'], ['沈1', '沈2']]];
//2.2添加数据
for (var i = 0; i < shengArr.length; i++) {
//select元素的option创建方式:【var option = new Option(‘想要显示的内容’);】
var opt = new Option(shengArr[i]);
//将创建的option添加到select内
shengSelect.options.add(opt);
}
//因为省的下标在市中需要使用提出成为 全局变量
var shengIndex = 0;
//2.3当省的数据发生改变时 要触发onchange事件
shengSelect.onchange = function () {
/*
获取选中省的下标
console.log('改变了',this.selectedIndex);
console.log('改变了',shengSelect.selectedIndex);
console.log('改变了',event.target.selectedIndex);
*/
shengIndex = this.selectedIndex - 1;
//当点击请选择时 清空所有的数据
if (shengIndex == -1) {
shiSelect.options.length = 0;
xianSelect.options.length = 0;
}else{
console.log(shengIndex);//0
//添加之前清空历史记录
shiSelect.options.length = 0;
for (var i = 0; i < shiArr[shengIndex].length; i++) {
//创建option
var opt = new Option(shiArr[shengIndex][i]);
//将option 添加到市select内
shiSelect.options.add(opt);
}
//当省的数据发生改变 该省下第一个市下所有县的数据展示出来
//添加之前清空历史记录
xianSelect.options.length = 0;
console.log(xianArr[shengIndex][0]);
for(var j = 0;j<xianArr[shengIndex][0].length;j++){
//创建option
var opt = new Option(xianArr[shengIndex][0][j]);
//将option添加到xianSelect内
xianSelect.options.add(opt);
}
}
};
//2.4当市的数据发生改变时 要触发onchange事件
shiSelect.onchange = function () {
//获取选择了哪一个市
var shiIndex = this.selectedIndex;
console.log(xianArr[shengIndex][shiIndex])
//添加之前清空县的数据
xianSelect.options.length = 0;
for(var i = 0;i<xianArr[shengIndex][shiIndex].length;i++){
//创建option
var opt = new Option(xianArr[shengIndex][shiIndex][i]);
//添加option
xianSelect.options.add(opt);
}
}