美文网首页我爱编程
《Javacript DOM 编程艺术》笔记(三)A JavaS

《Javacript DOM 编程艺术》笔记(三)A JavaS

作者: 红烧排骨饭 | 来源:发表于2018-05-27 14:29 被阅读0次

    这是最后一篇文章了,我所需要的知识到这里都结束了,书本剩余的内容都是一些最佳实践。应该在实践中遇到问题了再回来学习。

    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 href="https://dummyimage.com/600x400/000/fff&text=fireworks" title="A fireworks display" onclick = "showPic(this); return false;"> Fireworks</a>
            </li>
            <li>
                <a href="https://dummyimage.com/600x400/000/fff&text=coffee" title="A cup of black coffee" onclick = "showPic(this); return false;"> Coffee</a>
            </li>
            <li>
                <a href="https://dummyimage.com/600x400/000/fff&text=images/rose" title="A red, red rose" onclick = "showPic(this); return false;">Rose</a>
            </li>
            <li>
                <a href="https://dummyimage.com/600x400/000/fff&text=images/bigben" 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;
    }

    相关文章

      网友评论

        本文标题:《Javacript DOM 编程艺术》笔记(三)A JavaS

        本文链接:https://www.haomeiwen.com/subject/vnmbjftx.html