下拉式清單N級聯動,下拉聯動
一,後台需要提供以下格式的字串.
<select style="width: 125px; margin-left: 10px;"><option value="4">動作</option><option value="5">愛情</option><option value="7">恐怖</option></select><select style="width: 125px; margin-left: 10px;"><option value="8">XXX</option><option value="9">XXX</option><option value="10">XXX</option></select><select style="width: 125px; margin-left: 10px;"><option value="11">XXX</option></select>
二,js處理代碼.
$(function(){var url = ""; //擷取html的url$("#category_select_div").on("change","select",function(){var parentId = $(this).children('option:selected').val();var se = $(this).nextAll();if(se != null){se.remove();}$.post(url+parentId, function(data) {if(data != null && $.trim(data) != ""){$("#category_select_div").append(data);}var cId = $("#category_select_div select").last().children('option:selected').val();$("#category_id").val(cId);},"html");});});
三,html代碼.
<div id="category_select_div"><select style="width: 125px; margin-left: 10px;"><option value="1">電影</option><option value="2">電視</option><option value="3">綜藝</option></select></div><!-- 儲存ID值的input --><div><input id="category_id" type="hidden"/></div>
四,表結構如下:id,parent_id,name
1 0 電影
2 0 電視
3 0 綜藝
4 1 動作
5 1 愛情
6 1 戰爭
7 1 恐怖
......
五,幕後處理代碼:1,查詢sql語句:select id,parent_id,name from category t where t.parent_id = 1
2,擷取到的是一個List<Category> list;
3,
Integer parentId = 1;PrintWriter out = response.getWriter();StringBuffer html = null;List<Category> list = null;html = new StringBuffer("");do{list = categoryServices.selectListByParentId(parentId);//根據上面的sql語句查詢listif(list.size()>0){parentId = list.get(0).getId();for (int i = 0; i < list.size(); i++) {if(i==0){html.append("<select style=\"width: 125px;margin-left: 10px;\">");}html.append("<option value=\""+list.get(i).getId()+"\">"+list.get(i).getName()+"</option>");if(i==list.size()-1){html.append("</select>");}}}}while(list.size()>0);out.print(html.toString());out.flush();out.close();