位置:海鸟网 > IT > JavaScript >

简单实用的JavaScript两级联动示例

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>