您的位置:首页 > Web前端 > JavaScript

javascript 基础 获取元素并创建列表demo 2017-1-10

2017-01-10 00:01 531 查看
<!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 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>


/**
* Created by Administrator on 2017/1/9.
*/
function displayAbbreviations() {

if(!document.getElementsByTagName || !document.createElement || !document.createTextNode) return false;
//简单的兼容性测试 要是不兼容 则退出这个函数

var abbreviations = document.getElementsByTagName("abbr");
if (abbreviations.length < 1) return false;
var defs = new Array();
// 取得所有的词数组  并且创建一个准备存储的数组

for(var i=0;i<abbreviations.length;i++){
var definitions = abbreviations[i].getAttribute("title");
var key = abbreviations[i].lastChild.nodeValue;
defs[key] = definitions;
}
//开始遍历数组 存放到defs里面 里面的文本为key titile为value

var dllist = document.createElement("ul"); //创建一个ul列表

for(key in defs){
var definition = defs[key];
var dt = document.createElement("tr");
var dt_title = document.createTextNode(key);
dt.appendChild(dt_title);
var dd = document.createElement("td");
var dd_text = document.createTextNode(definition);
var lilist = document.createElement("li");
dd.appendChild(dd_text);
lilist.appendChild(dt);
lilist.appendChild(dd);
dllist.appendChild(lilist);
}

// 进行循环 把 defs数组里的 每个key挨个拿出来存储到key变量里  然后重复创建 链接 获取 最后把
// tr td 都存放到 li里 再把 li 存放到 最大的ul里

var h2 = document.createElement("h2");
var h2_text = document.createTextNode("abbrevition");
h2.appendChild(h2_text);
document.body.appendChild(h2);
document.body.appendChild(dllist);

// 结尾 把 h2节点与ul节点放入到 body的末尾中
}

window.onload = function () {
displayAbbreviations();
}

// 加载时运行


1.新的循环

for (variable in array)


他的意思是 当第一次循环时 把 array第一个元素的key也就是下标 放到variable中 第二次循环 把第二个元素的key放到variable中 一直到遍历完所有元素结束

2.引用body标签的方法有两种

第一种是DOM Core

document.getElementsByTagName("body")[0]


第二种是基于HTML DOM

document.body
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: