(DOM艺术) 第八章 充实文档内容一
- 用JS的DOM方法去处理一段HTML内容,从HTML结构中取得一些东西然后添加一些东西
explanation.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Explaining the Document Object Model</title>
<link rel="stylesheet" type="text/css" media="screen" href="styles/typography.css" />
<script type="text/javascript" src="scripts/addLoadEvent.js"></script>
<script type="text/javascript" src="scripts/displayAbbreviations.js"></script>
</head>
<body>
<h1>What is the Document Object Model?</h1>
<p>
The <abbr title="World Wide Web Consortium">W3C</abbr> defines
the <abbr title="Document Object Model">DOM</abbr> as:
</p>
<blockquote cite="http://www.w3.org/DOM/">
<p>
A platform- and language-neutral interface that will allow programs
and scripts to dynamically access and update the
content, structure and style of documents.
</p>
</blockquote>
<p>
It is an <abbr title="Application Programming Interface">API</abbr>
that can be used to navigate <abbr title="HyperText Markup Language">
HTML</abbr> and <abbr title="eXtensible Markup Language">XML
</abbr> documents.
</p>
</body>
</html>
displayAbbreviation.js:
function displayAbbreviations() {
if (!document.getElementsByTagName || !document.createElement || !document.createTextNode) return false;
// get all the abbreviations
var abbreviations = document.getElementsByTagName("abbr");
if (abbreviations.length < 1) return false;
var defs = new Array();
// loop through the abbreviations
for (var i=0; i<abbreviations.length; i++) {
var current_abbr = abbreviations[i];
if (current_abbr.childNodes.length < 1) continue;
var definition = current_abbr.getAttribute("title");
var key = current_abbr.lastChild.nodeValue;
defs[key] = definition;
}
// create the definition list
var dlist = document.createElement("dl");
// loop through the definitions
for (key in defs) {
var definition = defs[key];
// create the definition title
var dtitle = document.createElement("dt");
var dtitle_text = document.createTextNode(key);
dtitle.appendChild(dtitle_text);
// create the definition description
var ddesc = document.createElement("dd");
var ddesc_text = document.createTextNode(definition);
ddesc.appendChild(ddesc_text);
// add them to the definition list
dlist.appendChild(dtitle);
dlist.appendChild(ddesc);
}
if (dlist.childNodes.length < 1) return false;
// create a headline
var header = document.createElement("h2");
var header_text = document.createTextNode("Abbreviations");
header.appendChild(header_text);
// add the headline to the body
document.body.appendChild(header);
// add the definition list to the body
document.body.appendChild(dlist);
}
addLoadEvent(displayAbbreviations);
addLoadEvent.js:
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
oldonload();
func();
}
}
}
注意这个要注意点,在下一篇里面会讲到,一个兼容性的Bug
我用的Chrome,其实现在的现代浏览器用这本书的这个例子代码就会有问题了,如果多个JS。下一篇讲。