JS DOM编程艺术——JS图片库2—— JS学习笔记2015-7-9(第80天)

childNodes属性: element.childNodes

它是包含这个元素的全部子元素的数组;

nodeType属性: 每一个节点都有nodeType属性,这个属性可以让我们知道自己正在与哪种节点打交道

node.nodeType

返回 1 是指该节点为元素节点;

返回 2 是指该节点为属性节点;

返回 3 是指该节点为文本节点;

nodeValue属性:

node.nodeValue

但是这个属性在实际使用的时候需要配合childNodes才行,详情看例子

firstChild和lastChild

firstChild 等同于 node.childNodes[0];  只不过这种更加直观和语义化

同理 lastChild 等同于 node.childNodes[node.childNodes.length-1] 

实例:

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>gallery</title>
<style>
body { margin:1em 10%; color: #333; font-family: "Helvetica", "Arial", serif; background-color: #ccc;}
h1 { background-color: transparent;}
a { color: #c60; text-decoration: none; font-weight: bold; background-color: transparent;}
ul { padding: 0 }
li { float: left; padding: 1em; list-style: none; }
img { display: block; clear: both }

</style>
</head>

<body>
<h1>Snapshots</h1>
<ul>
    <li><a href="img/s1.jpg" onclick="showPic(this); return false" title = "A fireworks display">Fireworks</a></li>
    <li><a href="img/s2.jpg" onclick="showPic(this); return false" title = "A cup of black coffee">Coffee</a></li>
    <li><a href="img/s3.jpg" onclick="showPic(this); return false" title = "A red, red rose">Rose</a></li>
    <li><a href="img/s4.jpg" onclick="showPic(this); return false" title = "The famous clock">Big Ben</a></li>
</ul>
<img id="placeholder" src="img/s1.jpg" alt="my image gallery">
<p id="des">Choose an image.</p>
<script type="text/javascript" src="scripts/showPic.js"></script>
</body>
</html>

JS:

    function showPic(whichpic){
        
        var source = whichpic.getAttribute("href");
        var placeholder = document.getElementById("placeholder");
        placeholder.setAttribute('src', source);
        var text = whichpic.getAttribute("title");
        var des = document.getElementById("des");
        // alert(des.nodeValue);  // null
        // alert(des.childNodes[0].nodeValue); // 返回P标签里面的内容;
       des.firstChild.nodeValue = text;

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