JS DOM编程艺术——显示缩略语列表—— JS学习笔记2015-7-16(第85天)

缩略语列表函数

HTML 结构:

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>显示缩略语列表</title>
<style>
 body{ font-family: "Helvetiva", "Arial", sans-serif; font-size: 10pt;}
 abbr{ border: 0; font-style: normal;} 

</style>

</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>

  <script src="scripts/addLoadEvent.js"></script>
  <script src="scripts/displayAbbrevitions.js"></script>
</body>
</html>

js:

function addLoadEvent(func){

  var oldonload = window.onload;
  if (typeof window.onload != 'function') { 
    window.onload = func;
  } else{
    window.onload = function(){
        oldonload();
        func();
    }
  }
}


// displayAbbreviations.js
function displayAbbreviations(){
  // 取得所有缩略词
  var abbreviations = document.getElementsByTagName("abbr");
  if(abbreviations.length < 1) return false;
  var defs = new Array();
  // 遍历所有缩略词
  for( var i=0; i<abbreviations.length; i++){
   
      var current_abbr = abbreviations[i];
      var definition = current_abbr.getAttribute("title");
      var key = current_abbr.lastChild.nodeValue;
      defs[key] = definition;
  }
  // 创建定义列表
  var dlist = document.createElement("dl");
  // 遍历定义
  for( key in defs){
    var definition = defs[key];
    // 创建定义标题
    var dtitle = document.createElement("dt");
    var dtitle_text = document.createTextNode(key);  // 这里多了一个引号
    dtitle.appendChild(dtitle_text);
    // 创建定义描述
    var ddesc = document.createElement("dd");
    var ddesc_text = document.createTextNode("definition");
    ddesc.appendChild(ddesc_text);
    // 把它们添加到定义列表
    dlist.appendChild(dtitle);
    dlist.appendChild(ddesc);
  }
  // 创建标题
  var header = document.createElement("h2");
  var header_text = document.createTextNode("Abbreviations")
  header.appendChild(header_text);
  // 把标题添加到页面主体
  document.body.appendChild(header);
  // 把定义列表添加到页面主体
  document.body.appendChild(dlist);
}
addLoadEvent(displayAbbreviations);

这里面提到了一个for in 语句,其功能是用来枚举对象的属性;

语法:for  (property in expression) statement

例子:for (var propName in window){

               document.write(propName);

}

原文地址:https://www.cnblogs.com/zhangxg/p/4652942.html