JS操作节点经典案例(三级联动)

17 篇文章 0 订阅
8 篇文章 0 订阅

引入

通过JS操作DOM元素对象,实现三级联动,效果如图所示。
在这里插入图片描述

js代码

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>三级联动</title>
	</head>
	<body>
		<select name="province" id="province" onchange="changeP(this)">
			<option value="-1">--请选择省--</option>
		</select>
		<select name="city" id="city" onclick="changeC(this)">
			<option value="">--请选择市--</option>
		</select>
		<select name="area" id="area">
			<option value="">--请选择区--</option>
		</select>
	</body>
	<script>
		let arrP = ['湖南省', '湖北省', '广东省'];
		let arrC = [
			['长沙', '株洲', '吉首', '常德', '张家界'],
			['武汉', '襄阳', '随州', '宜昌', '荆州'],
			['广州', '台山', '佛山', '中山', '云浮']
		];
		let arrA = [
			[
				['长沙1', '长沙2', '长沙3', '长沙4', '长沙5'],
				['株洲1', '株洲2', '株洲3', '株洲4', '株洲5'],
				['吉首1', '吉首2', '吉首3', '吉首4', '吉首5'],
				['常德1', '常德2', '常德3', '常德4', '常德5'],
				['张家界1', '张家界', '张家界3', '张家界4', '张家界5']
			],
			[
				['武汉1', '武汉', '武汉3', '武汉4', '武汉5'],
				['襄阳1', '襄阳2', '襄阳3', '襄阳4', '襄阳5'],
				['随州1', '随州2', '随州4', '随州4', '随州5'],
				['宜昌1', '宜昌2', '宜昌3', '宜昌4', '宜昌5'],
				['荆州1', '荆州2', '荆州3', '荆州4', '荆州5']
			],
			[
				['广州1', '广州2', '广州', '广州4', '广州5'],
				['台山1', '台山2', '台山3', '台山4', '台山5'],
				['佛山1', '佛山2', '佛山3', '佛山4', '佛山5'],
				['中山1', '中山2', '中山3', '中山4', '中山5'],
				['云浮1', '云浮2', '云浮3', '云浮4', '云浮5']
			],
		];
		//添加省选择
		let province = document.getElementById('province');
		let area = document.getElementById('area');
		let city = document.getElementById('city');
		for (let i in arrP) {
			let op = document.createElement('option');
			op.setAttribute('value', arrP[i]);
			op.innerText = arrP[i];
			province.appendChild(op);
		}
		//省改变函数
		function changeP(provinceH) {
			let arr = arrC[provinceH.selectedIndex - 1];
			//让省份只留第一项
			if (typeof arr != 'undefined') {
				city.options.length = 0;
				for (let index in arr) { //创建Option对象可以直接设置文本内容和值
					city.options.add(new Option(arr[index], arr[index]));
				}
				changeC(city);
			} else {
				city.innerHTML = "<option value='-1'>--请选择市--</option>";
				area.innerHTML = "<option value='-1'>--请选择区--</option>";
			}
		}
		//区改变函数
		function changeC(cityH) {
			//防止为undefined时取数组值报错
			if (typeof arrA[province.selectedIndex - 1] != 'undefined') {
				let arr = arrA[province.selectedIndex - 1][cityH.selectedIndex];
				//让省份只留第一项
				area.options.length = 0;
				for (let index in arr) { //创建Option对象可以直接设置文本内容和值
					area.options.add(new Option(arr[index], arr[index]));
				}
			}
		}
	</script>
</html>

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值