JAVASCRIPT DOM编程艺术读书笔记
第四章 案例研究 JavaScript图片库
插入链接来引用javascript脚本,把他放在</body>之上
<script type = "text/javascript" src = "showpic.js"> </script>
事件处理函数,比如鼠标指针悬浮在一个元素上时候触发一个动作,就用onmouseover. 离开一个元素是触发 onmouseout 点击就是onclick
<li> <a href = "images/fireworks.jpg" title="A fireworks display" onclick="showPic(this); return false"> Fireworks</a></li> ##return false禁止点击的默认行为 仅仅将这个动作关联到函数showPic(this)
节点的类型总共有12种可取值,有3种具有实用价值: nodeType属性:返回节点的类型;node.nodeType(可用此来验证是否获得了自己想选择的节点)
- 元素节点的nodeType属性值是1
- 属性节点的nodeType属性值是2
- 文本节点的nodeType属性值是3
想要改变一个文本节点的值,可以使用nodeValue node.nodeValue
<p id = "description">Choose a image</p> alert(description.nodeValue);返回的将是一个null 因为这个返回的是<p>,<p>元素本身的nodeValue就是null 我们需要的是<p>里边包含的文本 包含在<p>里边的文本是另一种节点,他是p的第一个子节点,可以写作 alert(description.childNodes[0].nodeValue);或者alert(description.firstChild.nodeValue);
贴上本章的JS代码
function showPic(whichPic) { var source = whichPic.getAttribute("href"); //获取资源路径 var placeholder = document.getElementById("placeholder"); placeholder.setAttribute("src",source); var text = whichPic.getAttribute("title"); //获取内容 var description = document.getElementById("description"); description.firstChild.nodeValue = text; }