JavaScript_DOM编程艺术第六章——效果实现code

很多人都说自己打的第六章代码实现不出来,主要是prepareGallery()函数那块检查getElementsTagName会返回false

myjs.js

function addLoadEvent(func){
    var oldonload = window.onload;
    if(typeof window.onload != "function"){
        window.onload = func;
    }else{
        window.onload = function(){
            oldonload();
            func();
        }
    }
}

//编写函数,关联到onclick事件
function prepareGallery(){
    if(!document.getElementById )   return false;    
//  if(!document.getElementsTagName)    return false;    //代码效果不能实现的出错位置!!
    if(!document.getElementById("imagegallery"))    return false;
    var gallery = document.getElementById("imagegallery");
    var links = gallery.getElementsByTagName("a");
    for(var i=0; ifunction(){
            return !showPic(this);  
        }
    }
}

function showPic(whichpic){
    if(!document.getElementById("placeholder")) return false;
    var source = whichpic.getAttribute("href");     //源图片的位置指向
    var placeholder = document.getElementById("placeholder");//需要改变的属性对象
    if(placeholder.nodeName != "IMG") return false;
    placeholder.setAttribute("src",source); //改变对象的src属性值
    if(document.getElementById("description")){
        if(whichpic.getAttribute("title")){
            var text = whichpic.getAttribute("title");
        }else{
            var text = "";
        }
        var description = document.getElementById("description");
        if(description.firstChild.nodeType == 3){
            description.firstChild.nodeValue = text;    //文本节点的值替换为图片的title
        }
    }
    return true;
}



addLoadEvent(prepareGallery);

goods_dom.html源代码


<html>
    <head>
        <title> JavaScript图片库 title>
        <meta charset="utf-8"/>
        <link rel="stylesheet" href="css/layout.css" type="text/css"/>
    head>

    <body>
        <h1>Goodsh1>

        <ul id="imagegallery">  
            <li>

                <a href="images/01.jpg" title="goods_a" >
                    <img src="images/01.jpg" alt="a" />
                a>  
            li>
            <li>
                <a href="images/02.jpg" title="goods_b" >
                    <img src="images/02.jpg" alt="b" />
                a>
            li>
            <li>
                <a href="images/03.jpg" title="goods_c" >
                    <img src="images/03.jpg" alt="c" />
                a>
            li>
        ul>
        <img id="placeholder" src="images/00.jpg" alt="my image gallery" />
        <p id="description">Choose an image.p>
    <script type="text/javascript" src="scripts/myjs.js">script>
    body>

html>

可以实现啦!

你可能感兴趣的:(JavaScript_DOM编程艺术第六章——效果实现code)