级联下拉选择器

by DarcyAn

HTML

<form name="demoForm">
<select name="chapter">
<option>请选择章目录</option>
</select>
<select name="section">
<option>请选择节目录</option>
</select>
</form>

JavaScript

var chapters = [ 
    {text:'1. DOM基础',value:'1'}, 
    {text:'2. 事件模型',value:'2'} 
 ]; 
var sections = { 
    1:[ 
        {text:'1.1 文档树',value:'1.1'}, 
        {text:'1.2 节点操作',value:'1.2'}, 
        {text:'1.3 元素遍历',value:'1.3'}, 
        {text:'1.4 样式操作',value:'1.4'}, 
        {text:'1.5 属性操作',value:'1.5'}, 
        {text:'1.6 表单操作',value:'1.6'} 
    ], 
    2:[ 
        {text:'2.1 事件类型',value:'2.1'}, 
        {text:'2.2 事件模型',value:'2.2'}, 
        {text:'2.3 事件应用',value:'2.3'} 
    ] 
}; 
var demoForm = document.forms.demoForm;
function fillSelect(select, list){
  //先倒序遍历清空列表
  for(var i=select.length-1; i>0; i--){
    select.remove(i);
  }
  //然后把传入的数据列表list通过循环添加到option上去
  list.forEach(function(data){
    var option = new Option(data.text, data.value)
    select.add(option);
  })
}
fillSelect(demoForm.chapter, chapters);

demoForm.chapter.addEventListener("click", function(event){
  var value = event.target.value;
  //另一种获取value的方式demoForm.chapter.value
  var list = sections[value] || [];
  fillSelect(demoForm.section, list);
})