当前位置: 代码迷 >> JavaScript >> 札记:JS权威指南15章―脚本化文档
  详细解决方案

札记:JS权威指南15章―脚本化文档

热度:298   发布时间:2012-08-28 12:37:01.0
笔记:JS权威指南15章―脚本化文档

DOM HTML API

DOM 标准可以与 XML 文档和 HTML 文档一起使用。 DOM 的核心 API Node Element Document 和其他接口)相对通用一些,可以应用于这两种类型的文档。 DOM 标准还包括 HTML 文档专有的接口。 ?????? HTMLDociument HTML 专有的 Document 接口的子接口, HTMLElement HTML 专有的 Element 接口的子接口。

?

HTML 命名规则: HTML 专有的接口的属性应该以小写字母开头,如果属性名有多个单词构成,第二个单词以及接下来的每个单词的首字母都要大写。当 HTML 属性名与 Javascript 关键字冲突时,应在属性前加 html 来避免冲突(例外是 class 属性,对应为 className )。

<input> 标记的 maxlength 属性倍转换成 HTMLInputElement maxLenght 属性

<label> 标记的 for 属性 HTMLLabelElement 的属性 htmlFor

?

0 DOM (遗留 DOM ),有 Netscape IE W3C 标准化之前实现的 HTML 文档)、 1 DOM 2 DOM 3 DOM (仅有 firefox 支持其中的部分)

?

访问表单元素的等价方法:

var f = document.forms.namedItem("myform");
var g = document.forms["myform"];
var h = document.forms.myform;
?
//创建一个新Text节点
var t = document.createTextNode("new text node");
?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>document</title>
<script type="text/javascript">
function countTags(n) {
	var numtags = 0;
	if (n.nodeType == 1 /*NODE.ELEMENT_NODE*/) numtags++;
	
	var children = n.childNodes;
	for(var i=0; i < children.length; i++) {
		numtags += countTags(children[i]);
	}
	return numtags;	
}
</script>
</head>
<body onload="alert('文档中共有标签数:'+ countTags(document))">
<a href="#">11</a>
</body>
</html>

?

?

修改文档的方法:改变文本、重排节点、改变元素属性( element.setAttribute() )。

?

var headline = document.getElementById('headline');
headline.setAttribute('align', 'center');
?

?

?

DocumentFragment 是一种特殊类型的节点,它自身不出现在文档中,只是作为连续集合的临时容器,并允许将这些节点作为一个对象来操作。当把一个 DocumentFragment 插入文档是,插入的不是 DocumentFragment 自身,而是它的所有子节点。

?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>document</title>
<script type="text/javascript">
//对列表元素按字母排序
function sortKids(e) {
	if (typeof e == "string") e = document.getElementById(e);
	
	var kids = [];
	for(var x = e.firstChild; x != null; x = x.nextSibling){
		if (x.nodeType == 1 /*NODE.ELEMENT_NODE*/) kids.push(x);
	}
	
	kids.sort(function(n,m) {
		var s = n.firstChild.data;
		var t = m.firstChild.data;
		if (s < t) return -1;
		else if (s >t) return 1;
		else return 0;
	});
	for(var i = 0; i < kids.length; i++) e.appendChild(kids[i]);
}

//把一个节点的父节点重定为<b>元素
function embolden(n) {
	if (typeof n == 'string') n = document.getElementById(n);
	var b = document.createElement("b");
	var parent = n.parentNode;
	parent.replaceChild(b, n);
	b.appendChild(n);
}

//设置属性
function update(e) {
	if (typeof e == 'string') e = document.getElementById(e);
	e.setAttribute("align", "center");
}
</script>
</head>
<body>
    <ul id="list">
     <li class="active">one</li>
        <li>two</li>
        <li>three</li>
        <li>four</li>
        <li>five</li>
    </ul>
<p id="headline">这是第一个段落</p>
<button onclick="sortKids('list')">按字母排序</button>
<button onclick="embolden('list')">粗体显示</button>
<button onclick="update('headline')">居中显示</button>
</body>
</html>
?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>输出函数调试信息</title>
<script type="text/javascript">
function log(category, message, object) {
	//log.options.debugDisabled = true,则退出
	if (log.options[category + "Dsiabled"]) return;
	
	//找到log信息装载容器
	var id = category + "_log";
	var c = document.getElementById(id);
	
	//没有找到装载容器,并且log.options.debugEnabled = true,则创建容器
	if (!c && log.options[category + "Enabled"]) {
		c = document.createElement("div");
		c.id = id;
		c.className = "log";
		document.body.appendChild(c);
	}
	
	if (!c) return;
	
	if (log.options.timestamp) message = new Date() + ": " + (message ? message : "");
	
	//创建div保存log信息
	var entry = document.createElement("div");
	entry.className = category + "_message";
	
	if (message) {
		entry.appendChild(document.createTextNode(message));
	}
	
	if (Object && typeof Object == 'object') {
		entry.appendChild(log.makeTable(object, 0));
	}
	
	c.appendChild(entry);
}

//在表格中显示object属性
log.makeTable = function(object, level) {
	if (level > log.options.maxRecursion)
		return document.createTextNode(object, toString());
	
	//创建表格
	var table = document.createElement("table");
	table.border = 1;
	var header = document.createElement('tr');
	var headerName = document.createElement('th');
	var headerType = document.createElement('th');
	var headerValue = document.createElement('th');
	headerName.appendChild(document.createTextNode('Name'));
	headerType.appendChild(document.createTextNode('Type'));
	headerValue.appendChild(document.createTextNode('Value'));
	header.appendChild(headerName);
	header.appendChild(headerType);
	header.appendChild(headerValue);
	table.appendChild(header);
	
	//获取object的属性并按字母顺序排序
	var names = [];
	for(var name in object) names.push(name);
	names.sort();
	
	for(var i = 0; i < names.length; i++) {
		var name, value, type;
		name = names[i];
		try {
			value = object[name];
			type = typeof value;			
		} 
		catch(e) {
			value = "<unknown value>";
			type = "unknown";
		}
		
		if (log.options.filter && !log.options.filter(name, value)) continue;
		
		if (type == 'function') value = "(/*暂无数据*/)";
		
		var row = document.createElement('tr');
		row.vAlign = "top";
		var rowName = document.createElement("td");
		var rowType = document.createElement("td");
		var rowValue = document.createElement("td");
		rowName.appendChild(document.createTextNode(name));
		rowType.appendChild(document.createTextNode(type));
		
		if (type == 'object') 
			rowValue.appendChild(log.makeTable(value, level + 1));
		else
			rowValue.appendChild(document.createTextNode(value));
		
		row.appendChild(rowName);
		row.appendChild(rowType);
		row.appendChild(rowValue);
		table.appendChild(row);
	}
	return table;
}
log.options = {};

log.debug = function(message, object) { log("debug", message, object);};
log.warn = function(message, object) { log("warning", message, object);};

</script>
<style type="text/css">
#debug_log {
	background-color : #aaa;
	border : solid black 2px;
	overflow : auto;
	width : 75%;
	height : 300px;
}
#debug_log:before {
	content : "Debugging Messages";
	display : block;
	text-align : center;
	font : bold 18px sans-serif;
}
.debug_message {
	border-bottom : solid black 1px;
}
</style>
</head>
<body>
<script type="text/javascript">
function makeRectangle(x, y, w, h) {
    //待调试的函数
	log.debug("entering makeRectangle");
	var r = {x : x, y : y, size : {w : w, h : h}};
	log.debug("New rectangle", r);
	log.debug("exiting makeRectangle");
	return r;	
}

//创建元素
//make("p",["this is a ", make("b", "bold"), " word."]);
function make(tagname, attributes, children) {
	if (arguments.length == 2 && (attributes instanceof Array || typeof attributes == 'string')) {
		children = attributes;
		attributes = null;
	}
	
	var e = document.createElement(tagname);
	
	//设置属性
	if (attributes) {
		for(var name in attributes) e.setAttributes(name, attributes[name]);
	}

	if (children != null) {
		//如果属性参数是数组
		if (children instanceof Array) {
			for(var i = 0; i < children.length; i++) {
				var child = children[i];
				if (typeof child == 'string')
					child = document.createTextNode(child);
				e.appendChild(child);
			}
		}
		else if (typeof children == 'string') {//属性参数是字符串
			e.appendChild(document.createTextNode(children));			
		}
		else e.appendChild(children);
	}
	return e;
}
</script>
<button onclick="makeRectangle(1, 2, 3, 4);">创建矩形</button>
<div id="debug_log" class='log'></div>
</body>
</html>
?

?

动态创建目录

?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>动态创建的目录</title>
<style type="text/css">
#toc {
	background : #ddd;
	border : solid black 1px;
	margin : 10px;
	padding : 10px;
}
.TOCEntry { font-family : sans-serif;}
.TOCEntry a { text-decoration : none;}
.TOCLevel1 { font-size : 16px; font-weight : bold;}
.TOCLevel2 { font-size : 12px; margin-left : 5in;}
.TOCBackLink { display : block;}
.TOCSectNum:after { content : ":";}
</style>
</head>
<script type="text/javascript">
function maketoc() {
	//找到容器,如无则退出
	var container = document.getElementById('toc');
	if (!container) return;
	
	//遍历文档,将所有<h1>...<h6>添加到数组
	var sections = [];
	findSections(document, sections);
	
	//在容器前插入锚
	var anchor = document.createElement('a');
	anchor.name = "TOCtop";
	anchor.id = "TOCtop";
	//在TOC前添加
	container.parentNode.insertBefore(anchor, container); 
	
	//初始化一个数组记录区块数字
	var sectionNumbers = [0,0,0,0,0,0];
	
	//循环找到的区块头部元素
	for(var s = 0; s < sections.length; s++){
		var section = sections[s];
		
		var level = parseInt(section.tagName.charAt(1));
		if (isNaN(level) || level < 1 || level > 6) continue;
		
		sectionNumbers[level-1]++;
		for(var j = level; j < 6; j++) {
			sectionNumbers[j] = 0;
		}
		
		var sectionNumber = "";
		for(var i = 0; i < level; i++) {
			sectionNumber += sectionNumbers[i];
			if (1 < level - 1) sectionNumber += ".";
		}
		
		var frag = document.createDocumentFragment();
		var span = document.createElement('span');
		span.className = "TOCSectNum";
		span.appendChild(document.createTextNode(sectionNumber));
		frag.appendChild(span);
		frag.appendChild(document.createTextNode(" "));
		section.insertBefore(frag, section.firstChild);
		
		var anchor = document.createElement('a');
		anchor.name = "TOC" + sectionNumber;
		anchor.id = "TOC" + sectionNumber;
		
		var link = document.createElement("a");
		link.href = "#TOCtop";
		link.className = "TOCBackLink";
		link.appendChild(document.createTextNode(maketoc.backlinkText));
		anchor.appendChild(link);
		
		section.parentNode.insertBefore(anchor, section);
		
		var Link = document.createElement("a");
		Link.href = "#TOC" + sectionNumber;
		Link.innerHTML = section.innerHTML;
		
		var entry = document.createElement("div");
		entry.className = "TOCEntry TOCLevel" + level;
		entry.appendChild(Link);
		
		container.appendChild(entry);		
	}
	
	function findSections(n, sects) {
		for(var m = n.firstChild; m != null; m = m.nextSibling) {	
			if (m.nodeType != 1/*NODE.ELEMENT_NODE*/) continue;			
			if (m == container) continue;	
			if (m.tagName == "P") continue;
			
			if (m.tagName.length == 2 && m.tagName.charAt(0) == "H") sects.push(m);			
			else findSections(m, sects);		
		}		
	}
}
maketoc.backlinkText = "Contents";

//文档加载完毕自动运行maketoc
if (window.addEventListener) window.addEventListener("load", maketoc, false);
else if (window.attachEvent) window.attachEvent("onload", maketoc);
</script>
<body>
<div id="toc">
	<h1>表格的内容</h1>
</div>
	<h2>动态文档内容</h2>
	<h3>遗留DOM</h3>
	<P>命名文档对象</P>
	<P>文档模型中的时间驱动</P>
	<P>遗留DOM例子</P>
	<h4>W3C DOM综述</h4>
</body>
</html>
?
  相关解决方案