JavaScript省级联动
2016-08-05 16:44
288 查看
省:<select id="pro"><option value="">请选择省</option>
<option value="1">北京</option>
<option value="2">上海</option>
<option value="3">广西</option></select>
市:<select id="city"><option value="">请选择市</option></select>
<script>
//市数据结构,为json数组对象。数组小标为省的id,数组项为市json数据。如果还有县的联动,同理生成arrTown即可。
var arrCity = [];
arrCity[1] = [{ t: '北京市', id: 1}];
arrCity[2] = [{ t: '上海市', id: 2}];
arrCity[3] = [{ t: '南宁市', id: 3 }, { t: '桂林市', id: 4 }, { t: '柳州市', id: 5}];
document.getElementById('pro').onchange = function () {
addOptions(document.getElementById('city'), arrCity[this.value]);
}
function addOptions(s, arr, initValue) {
if (!arr || arr.length == 0) arr = [{ t: '请选择市', id: ''}];
if (!s) { alert('select对象不存在!'); return false }
s.options.length = 0;
var selectedIndex = 0;
for (var i = 0; i < arr.length; i++) {
s.options.add(new Option(arr[i].t, arr[i].id));
if (arr[i].id == initValue) selectedIndex = i;
}
}
</script>
<option value="1">北京</option>
<option value="2">上海</option>
<option value="3">广西</option></select>
市:<select id="city"><option value="">请选择市</option></select>
<script>
//市数据结构,为json数组对象。数组小标为省的id,数组项为市json数据。如果还有县的联动,同理生成arrTown即可。
var arrCity = [];
arrCity[1] = [{ t: '北京市', id: 1}];
arrCity[2] = [{ t: '上海市', id: 2}];
arrCity[3] = [{ t: '南宁市', id: 3 }, { t: '桂林市', id: 4 }, { t: '柳州市', id: 5}];
document.getElementById('pro').onchange = function () {
addOptions(document.getElementById('city'), arrCity[this.value]);
}
function addOptions(s, arr, initValue) {
if (!arr || arr.length == 0) arr = [{ t: '请选择市', id: ''}];
if (!s) { alert('select对象不存在!'); return false }
s.options.length = 0;
var selectedIndex = 0;
for (var i = 0; i < arr.length; i++) {
s.options.add(new Option(arr[i].t, arr[i].id));
if (arr[i].id == initValue) selectedIndex = i;
}
}
</script>
相关文章推荐
- JQuery1——基础($对象,选择器,对象转换)
- Android学习笔记(二九):嵌入浏览器
- Android java 与 javascript互访(相互调用)的方法例子
- JavaScript演示排序算法
- javascript实现10进制转为N进制数
- 最后一次说说闭包
- Ajax
- 2019年开发人员应该学习的8个JavaScript框架
- HTML中的script标签研究
- 对一个分号引发的错误研究
- 设计模式---状态模式在web前端中的应用
- 异步流程控制:7 行代码学会 co 模块
- ES6 走马观花(ECMAScript2015 新特性)
- JavaScript拆分字符串时产生空字符的原因
- Canvas 在高清屏下绘制图片变模糊的解决方法
- Redux系列02:一个炒鸡简单的react+redux例子