【DOM编程艺术】显示"文献来源链接表"

<!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>explaining</title>
</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 the style of document.</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>
<script>
addLoadEvent(displayCitations);
function displayCitations(){
    if( !document.getElementsByTagName || !document.getElementById || !document.createTextNode ) return false;
    var quotes=document.getElementsByTagName('blockquote');
    for(var i=0;i<quotes.length;i++){
        if( !quotes[i].getAttribute('cite')) continue;   //使用continue立刻跳到下一次循环
        var url=quotes[i].getAttribute('cite');
        var quoteElements=quotes[i].getElementsByTagName('*');
        if( quoteElements.length < 1) continue;
        var elem=quoteElements[quoteElements.length-1];
        var link=document.createElement('a');
        link.setAttribute('href',url);
        var link_text=document.createTextNode('source');
        link.appendChild(link_text);
        var superscript=document.createElement('sup');
        superscript.appendChild(link);
        elem.appendChild(superscript);
        console.log(elem);
    }
}
function addLoadEvent(func){
    var oldEvent = window.onload;
    if( typeof window.onload != 'function'){
        window.onload=func;
    }else{
        window.onload=function(){
             oldEvent();
            func();
        }
    }
}
</script>
</body>
</html>

解析:

<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 the style of document.</P>
</blockquote>

结果<TextNode textContent="\n">  

找到blockquote下的块级元素,若用document.getElementsByTagName('blockquote').lastChild  乍看起来,是查找到最后一个元素

事实上,那个p节点的确是blockquote元素的最后一个元素节点,但在</p>和</blockquote>标签之间还存在一个换行符。有些浏览器会

把这个换行符解释为一个文本节点。这样一 来,blockquote元素节点的lastChild属性就将是一个文本节点而不是元素节点。

解决方法:查找所有的元素节点,最后一个元素节点即为p

document.getElementsByTagName('blockquote').getElementsByTagName('*')[length-1]

posted @ 2014-04-19 23:11  Western Journey  阅读(209)  评论(0编辑  收藏  举报