`

菜单联动的实现一(下拉框的onchange事件)

阅读更多

1、编写测试表单

     

 <form name="form">
      <p>
	<select name="Drop1" onChange="changeDrop2()" size="1">
	          <option selected value="Select A Product">
		Select A Top Category
	          </option>
	          <%
	               for (Category top : topCategories) {
	          %>
	         <option value="<%=top.getId()%>"><%=top.getName()%></option>
	         <%//填充以及下拉框信息
	             }
	         %>
	</select>
	<br>
	<select name="Drop2" size="1">

	</select>
	<br>
    </p>
</form>

 

2、先定义两个方法,然后调用这两个方法

       定义

         

<%!private List<Category> getTopCategories(List<Category> categories) {//得到第一层目录信息
		List<Category> topCategories = new ArrayList<Category>();
		for (int i = 0; i < categories.size(); i++) {
			Category c = categories.get(i);
			if (c.getGrade() == 1) {//grade为1时,为第一层目录
				topCategories.add(c);
			}
		}
		return topCategories;
	}

	private List<Category> getChilds(Category parent, List<Category> categories) {
		List<Category> childs = new ArrayList<Category>();
		for (int i = 0; i < categories.size(); i++) {
			Category c = categories.get(i);
			if (c.getPid() == parent.getId()) {//孩子节点的父ID号等于父节点的ID号时
				childs.add(c);
			}
		}
		return childs;
	}//得到parent目录下的所有子目录信息

	%>

   调用

        

List<Category> topCategories = getTopCategories(categories);//得到第一层目录信息

3、javascript实现代码

   

<script LANGUAGE="JavaScript">
      function changeDrop2() {
	if (document.form.Drop1.selectedIndex == 0) {//如果以及下拉框未选
		document.form.Drop2.length = 1;
		document.form.Drop1.selectedIndex = 0
		document.form.Drop2.selectedIndex = 0
		document.form.Drop2.options[0].text = "No Top Category Selected";
		document.form.Drop2.options[0].value = "No Top Category Selected";
	}

	<% for(Category top : topCategories) { %>
	
		if (document.form.Drop1.options[document.form.Drop1.selectedIndex].value == <%=top.getId()%>) {
			<%
			List<Category> childs = getChilds(top, categories);//查询选中目录下的所有子目录信息
			int i = 1;
			%>//动态填充二级下拉框信息
			document.form.Drop2.length = <%=childs.size() + 1%>;
			document.form.Drop2.selectedIndex = 0
			document.form.Drop2.options[0].text = "Select Second Category";
			document.form.Drop2.options[0].value = "Select Second Category";
			
			<% for (Category child : childs) { %>
				document.form.Drop2.options[<%=i%>].text = "<%=child.getName()%>";
				document.form.Drop2.options[<%=i%>].value = "<%=child.getId()%>";
				
			<%
				i ++; 
			} 
			%>
			
			}
	<% } %>

}
</script>

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics