JAVASCRIPT DOM编程艺术读书笔记
第八章 充实文档内容
function displayAbbreviation() { if (!document.getElementsByTagName || !document.createElement || !document.createTextNode) return false; var des = new Array(); var abbrevitation = document.getElementsByTagName("abbr"); //遍历所有的abbr for(var i = 0; i < abbrevitation.length; i++) { /*IE6之前的浏览器不支持abbr,在统计abbr的子节点时总返回错误的值0(由于当年的浏览器战争)*/ if(abbrevitation[i].childNodes.length < 1) continue; var definition = abbrevitation[i].getAttribute("title"); //将所有的abbr的title取出 是字符串 var keys = abbrevitation[i].lastChild.nodeValue; //将所有的abbr所包含的文本节点的内容取出 des[keys] = definition; //定义关联数组 循环可以用 for(keys in des) } var dlist = document.createElement("dl"); for(keys in des) { var definition = des[keys]; var dtitle = document.createElement("dt"); var dt_txt = document.createTextNode(keys); dtitle.appendChild(dt_txt); var ddesc = document.createElement("dd"); var dd_txt = document.createTextNode(definition); ddesc.appendChild(dd_txt); dlist.appendChild(dtitle); dlist.appendChild(ddesc); } if(dlist.childNodes.length < 1) return false; //创建一个二级标题 var h2_header = document.createElement("h2"); var h2_header_txt = document.createTextNode("Abbreviations"); h2_header.appendChild(h2_header_txt); document.body.appendChild(h2_header); document.body.appendChild(dlist); }
function displayCitations() { if (!document.getElementsByTagName || !document.createElement || !document.createTextNode) return false; var quotes = document.getElementsByTagName("blockquote"); for(var i = 0; i < quotes.length; i++) { //如果没有cite属性,继续 if(!quotes[i].getAttribute("cite")) continue; var url = quotes[i].getAttribute("cite"); console.log(url); //取得引用中所有的元素节点,在最后追加新添的元素 var quotes_child = quotes[i].getElementsByTagName("*"); if(quotes_child.length < 1) continue; //取得引用中最后一个元素节点,为何不直接用lastChild属性 /*
<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和/blcokquote之间有一个回车键,这个回车键可能会被认为最后一个节点,是一个文本节点.当然我们也可以检查nodeType的值 */ var last_elem = quotes_child[quotes_child.length - 1]; var link = document.createElement("a"); link.setAttribute("href",url); var link_txt = document.createTextNode("source"); link.appendChild(link_txt); //sup元素,在浏览器中呈现出上标的效果!!! var superscript = document.createElement("sup"); superscript.appendChild(link); last_elem.appendChild(superscript); } }