下拉条的连动-一般方式

<select id="category1" onchange="changecategory()">
    <option>所有一级类别</option>
   <%
    for(int i=0; i<topCategorys.size(); i++) {
     Category c = topCategorys.get(i);
   %>
      <option value="<%=c.getId() %>"><%=c.getName() %></option>
   <%
    }
    %>
   </select>
   <select id="category2">
    <option>所有二级类别</option>
   </select>

----------------------------------------------------------------------------------------------------------------------

<%!
 private String getSecondCategoryStr(List<Category> categorys, Category topCategory){
  StringBuffer buff = new StringBuffer();
  //buff.append("if(document.getElementById('category1').selectedIndex == " + topCategory.getId() + ") {\n");
  int childCount = 1;
  for(int i=0; i<categorys.size(); i++) {
   Category c = categorys.get(i);
   if(c.getPid() == topCategory.getId()) {
    buff.append("document.getElementById('category2').options[" + childCount + "].text = '" + c.getName() + "';\n");
    buff.append("document.getElementById('category2').options[" + childCount + "].value = '" + c.getId() + "';\n");
    childCount ++;
   }
   
  }
  buff.insert(0,"document.getElementById('category2').options[0].text = '所有二级类别';\n");
  buff.insert(0,"document.getElementById('category2').options[0].value = '-1';\n");
  buff.insert(0, "document.getElementById('category2').selectedIndex = 0;\n");
  buff.insert(0, "document.getElementById('category2').length = " + childCount + ";\n");
  buff.insert(0, "if(document.getElementById('category1').options[document.getElementById('category1').selectedIndex].value == " + topCategory.getId() + ") {\n");
  buff.append("}\n");
  return buff.toString();
 }
%>

--------------------------------------------------------------------------------------------------------------------------
<%
 List<Category> categorys = CategoryMgr.getInstance().getCategorys();
 List<Category> topCategorys = new ArrayList<Category>();
 String str = "";
 for(int i=0; i<categorys.size(); i++) {
  Category c = categorys.get(i);
  if(c.getGrade() == 1) {
   topCategorys.add(c);
   str += getSecondCategoryStr(categorys, c);
  }
 }
 %>

------------------------------------------------------------------------------------------------------------------------------------

<script type="text/javascript">
  function changecategory() {
   <%=str %>
  }
 </script>

posted on 2013-08-09 17:45  凯特的宝贝世界  阅读(170)  评论(0编辑  收藏  举报