2009-11-04

最简单的JavaScript两级联动示例

Views: 13088 | Add Comments

JavaScript两级联动, 比如表单里面有两个下拉菜单,实现关联,根据第一个下拉菜单选择的内容,在第二个下拉菜单中显示对应的选项. 这项功能非常有用, 但新手仍会需要示例.

将下列代码保存到一个后缀为.html的文本文件, 然后用浏览器打开即可:

<form method="post" action="">
	<select name="a" id="s1" onchange="on_s1_selected()">
		<option value="1">1</option>
		<option value="2">2</option>
		<option value="3">3</option>
	</select>

	<select name="b" id="s2">
	</select>
</form>

<script type="text/javascript">
<!--
var data = {};
data['1'] = ['1.1', '1.2', '1.3'];
data['2'] = ['2.1', '2.2', '2.3'];
data['3'] = ['3.1', '3.2', '3.3'];

var s1 = document.getElementById('s1');
var s2 = document.getElementById('s2');

function on_s1_selected(){
	var children = data[s1.value];	
	s2.innerHTML = '';

	var str = '';
	for(var i in children){
		var c = children[i];		
		var opt = document.createElement("option");
		opt.value = c;
		opt.innerHTML = c;
		s2.appendChild(opt);
	}
}
//-->
</script>

Related posts:

  1. 用Javascript生成弹出窗口
  2. 开发跨浏览器JavaScript—《Ajax基础教程》笔记
  3. JavaScript分页控件
  4. JavaScript 设置浏览器标题闪动
  5. 轻量级 COMET 服务器 icomet 支持 EventSource(SSE)
Posted by ideawu at 2009-11-04 16:40:15 Tags:

Leave a Comment