《Javacript DOM 編程藝術》筆記(三)A JavaScript Image Gallery [完結]

這是最后一篇文章了,我所需要的知識到這里都結束了,書本剩余的內容都是一些最佳實踐。應該在實踐中遇到問題了再回來學習。

A JavaScript Image Gallery

  • childNodes
  • nodeType
  • nodeValue
  • firstChild
  • lastChild

Image Gallery

gallery.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>Image Galerry</title>
    <script type="text/javascript" src="showPic.js"></script>
</head>
<body>
    <h1>Snapshots</h1>
    <ul>
        <li>
            <a  title="A fireworks display" onclick = "showPic(this); return false;"> Fireworks</a>
        </li>
        <li>
            <a  title="A cup of black coffee" onclick = "showPic(this); return false;"> Coffee</a>
        </li>
        <li>
            <a  title="A red, red rose" onclick = "showPic(this); return false;">Rose</a>
        </li>
        <li>
            <a  title="The famous clock" onclick = "showPic(this); return false;"> Big Ben</a>
        </li>
    </ul>
    <img id="placeholder" src="https://dummyimage.com/600x400/789/FFF&text=placeholder" alt="my image gallery" />    
</body>
</html>

showPic.js

function showPic(whichpic) {
    var source = whichpic.getAttribute("href");
    var placeholder = document.getElementById("placeholder");
    placeholder.setAttribute("src", source);
}

childNodes

function countBodyChildren() {
    var body_element = document.getElementsByTagName("body")[0];
    console.log(body_element.childNodes.length);
}

window.onload = countBodyChildren;

nodeType property

 var body_element = document.getElementsByTagName("body")[0];
console.log('body_element.nodeType = ' + body_element.nodeType);
  • Element nodes have a nodeType value of 1.
  • Attribute nodes have a nodeType value of 2.
  • Text nodes have a nodeType value of 3.

Adding a description in the markup

gallery.html 添加一個標簽

<p id="description">Choose an image.</p>

修改 showPic.js 的 showPic 方法

function showPic(whichpic) {
    // ...

    var text = whichpic.getAttribute("title");
    var description = document.getElementById("description");
    description.firstChild.nodeValue = text;
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 前言 歸根結底,代碼都是思想和概念的體現(xiàn)。沒人能把一種程序設計語言的所有語法和關鍵字都記住,可以查閱參考書來解決。...
    朱細細閱讀 2,979評論 4 14
  • "use strict";function _classCallCheck(e,t){if(!(e instanc...
    久些閱讀 2,054評論 0 2
  • 每一個國家,每一個地區(qū),每一個企業(yè)都喜歡建設代表各自身份的地標性建筑,比如英國倫敦的大本鐘,陜西西安的大雁塔,湖北...
    憶東風閱讀 886評論 1 1
  • 大大沙場秋點兵, 三軍威武眾志成。 裝甲長驅如猛虎, 戰(zhàn)機翱翔似蒼鷹。 列陣受閱朱日和, 鐵血健兒舉世驚。 揚我國...
    超級賦能王張勝萍閱讀 586評論 10 7
  • 找了好久,在stackoverflow上找到一個修改辦法 這個是跑在CENTOS和RHEL7上才能用到以下辦法 T...
    高機動老王閱讀 230評論 0 0