【ife】任务二十四:JavaScript和树(三)

2017-01-03 19:16:17来源:作者:人点击

var buttons = document.getElementsByTagName('button');var divs = document.getElementsByTagName('div');var city = document.getElementById("city");var nodes, node; for (var i = 0; i < divs.length; i++) {	divs[i].onclick = function(event) { 		select(event, this);	};}buttons[0].onclick = function() {	var value = document.getElementsByTagName('input')[0].value;	deepTraversal(city);	var textNode = document.createTextNode(value);	var divNode = document.createElement("div");	divNode.setAttribute("class", "direction"); 	divNode.appendChild(textNode);	for (var i = 0; i < nodes.length; i++) {		if (nodes[i] == node) {			nodes[i].appendChild(divNode);			divNode.onclick = function(event) { 				select(event, this);			};			break;		}	}	clear();}buttons[1].onclick = function() {	deepTraversal(city);	for (var i = 0; i < nodes.length; i++) {		if (nodes[i] == node) {			for (var j = 0; j < nodes[i].children.length; j++)				nodes[i].removeChild(nodes[i].children[j]);			nodes[i].parentNode.removeChild(nodes[i]);			break;		}	}	clear();}function select(e, selectNode) { 	if (e && e.stopPropagation)		e.stopPropagation(); 	else  		window.event.cancelBubble=true; 	deepTraversal(city);	node = selectNode;	for (var i = 0; i < nodes.length; i++) 		if (nodes[i] == selectNode)			nodes[i].style.background = "blue";	clear();}function clear() {	node = null; 	nodes = [];	for (var i = 0; i < divs.length; i++) 		divs[i].style.background = "white";}function deepTraversal(root) {	if (root != null) {  nodes.push(root);  var children = root.children;  for (var i = 0; i < children.length; i++)  deepTraversal(children[i]);}  }

最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台