DOM是document object model的缩写。其中,
D:当创建了一个网页,并加载到浏览器时,就产生了DOM,它将为网页内容创建一个文档。
O:文档中的每个节点都是一个对象,比如元素节点,属性节点,文本节点。
M:模型,即文档以何种形式显示出来。
DOM中常用的方法有4个:
- getElementById(),通过id来来获取对象
- getElementsByTagName(),通过标签名字来获取对象
- getAttribute()
- setAttribute()
有几点需要注意:
1、前两者有document来调用,后两者由节点对象来调用
2、getElementsByTagName()返回的是对象数组
下面给出一个小例子来说明以上几个方法的使用:
<html>
<head>
<meta http-equiv = "content-type" content = "text/html; charset = utf-8" />
<title>Image Gallery</title>
<script language = "javascript">
function showPic(whichPic)
{
var source = whichPic.getAttribute("href"); //获得源
var holder = document.getElementById("placeholder");
holder.setAttribute("src", source);
}
function countBodyChildren()
{
var body_element = document.getElementsByTagName("li");
alert(body_element.length);
}
window.onload = countBodyChildren;
</script>
</head>
<body>
<h1>Snapshots</h1>
<ul>
<li>
<a href = "1.jpg" title = "picture1" onclick = "showPic(this); return false;">picture1 </a>
</li>
<li>
<a href = "2.jpg" title = "picutre2" onclick = "showPic(this); return false;">picture2 </a>
</li>
<li>
<a href = "3.jpg" title = "picture3" onclick = "showPic(this); return false;">picture3 </a>
</li>
</ul>
<img id = "placeholder" src = "4.jpg" alt = "my placeholder" />
<p id = "description">choose an iamge</p>
</body>
</html>
说明:1、四张图片,命名为1.jpg,2.jpg,3.jpg,4,jpg,与所创建的html文档放在一个文件夹里
2、上述代码要实现的功能是,有三个链接,点击一个,就用其对应的图片来取代用作占位符的图片4