基于js——联动菜单的实现
以省市二级联动为例:
html:
1 <select name="provs"> 2 <option>—请选择—</option><!--0--> 3 <option>北京市</option><!--1--> 4 <option>天津市</option> 5 <option>河北省</option> 6 </select> 7 <select name="cities" class="hide"> 8 </select>
css: 这里使市级菜单在开始时隐藏
.hide{ display: none; }
然后开始用js写联动
var cities=[ [{"name":'东城区',"value":101}, {"name":'西城区',"value":102}, {"name":'海淀区',"value":103}, {"name":'朝阳区',"value":104}], [{"name":'河东区',"value":201}, {"name":'河西区',"value":202}, {"name":'南开区',"value":203}], [{"name":'石家庄市',"value":301}, {"name":'廊坊市',"value":302}, {"name":'保定市',"value":303}, {"name":'唐山市',"value":304}, {"name":'秦皇岛市',"value":305}] ]; var selProvs=document.querySelector("[name=provs]"); var selCts=document.querySelector("[name=cities]"); selProvs.onchange=function(){ var i=this.selectedIndex-1; if(i<0) selCts.className="hide"; else{ var cts=cities[i]; selCts.innerHTML=""; var frag=document.createDocumentFragment(); //用文档片段对象来添加多个平级子元素 var opt=document.createElement("option"); opt.innerHTML="-请选择-"; frag.appendChild(opt); for(var i=0;i<cts.length;i++){ var opt=document.createElement("option"); opt.innerHTML=cts[i]["name"]; opt.value=cts[i]["value"]; frag.appendChild(opt); } selCts.appendChild(frag); selCts.className=""; } }
最后给出联动菜单的思路即,将前一菜单的序号传入下一菜单,在通过添加元素将相应的二级选项添加到二级菜单中。