做完JavaScript DOM Interfaces的培训,写了一个例子,结合XMLHttpRequest用86行代码实现的树形菜单。原理很简单每个节点就是一个div,每点击一个节点的图片就通过XMLHttpRequest把这个节点的所有子节点从jsp文件里装载到父节点的div里。
具体看代码吧
js 代码
-
- var request = null;
-
- var currentNode = null;
- var url = null;
-
- var states = new Array();
-
- function ready(inUrl){
- try{
- request =new XMLHttpRequest();
- }catch(e){
- request =new ActiveXObject("Microsoft.XMLHTTP");
- }
- request.onreadystatechange=loadNode;
- url=inUrl;
- }
-
- function loadNode(){
- if(request.readyState==4){
- if (request.status == 200||request.status == 0) {
-
- var newContent = request.responseText;
-
- dataHit = document.getElementById("dataHit");
- if(dataHit!=null)
- currentNode.removeChild(dataHit);
-
- content=document.createElement("div");
- content.setAttribute("luck","true");
- content.innerHTML = newContent;
- currentNode.appendChild(content);
- }
- }
- }
-
- function loadTree(url,id){
- ready(url);
- var sel = document.getElementById(id);
-
- currentNode = sel;
- open(id);
- }
-
- function doclick(id){
- var sel = document.getElementById(id);
- currentNode = sel;
- if(states[id]=="opened"){
- close(id);
- states[id]="closed";
- }else{
- open(id);
- states[id]="opened";
- }
- }
-
- function open(id){
-
-
- dataHit=document.createElement("div");
- dataHit.setAttribute("id","dataHit");
-
- text=document.createTextNode("正在装载数据...");
- dataHit.appendChild(text);
- currentNode.appendChild(dataHit);
- try{
- img = document.getElementById("img"+id);
- img.setAttribute('src',"img/folderopen.gif");
- }catch(e){}
-
- ready(url);
-
- request.open('GET',url+"?id="+id+"&randnum=" + Math.random(),true);
- request.send(null);
- }
-
- function close(id){
-
- allnodes=currentNode.getElementsByTagName("div");
- for(var i=0;i
- currentNode.removeChild(allnodes.item(i));
- }
-
- img = document.getElementById("img"+id);
- img.setAttribute('src',"img/folder.gif");
- }
使用的html代码
xml 代码
- >
- <HTML>
- <HEAD>
- <TITLE> 动态树 <!---->TITLE>
- <link rel="StyleSheet" href="tree.css" type="text/css" />
- <script type="text/javascript" src="tree.js"><!---->script>
- <!---->HEAD>
- <BODY>
- <div id="tree">
- <!---->div>
- <SCRIPT LANGUAGE="JavaScript">
- <!---->
- loadTree('treenode.jsp','tree');
- //-->
- <!---->SCRIPT>
- <!---->BODY>
- <!---->HTML>
最后,十分偷懒的jsp代码
贴代码太麻烦
放附件里了