用getElementsByTagName和getElementById获取该元素的属性为什么效果不一样?

HTML代码

<h1>Amy</h1>
<ul>
    <li>
        <a href = "img/amy-1.jpg" onclick="showPic(this);return false;" title = "amy1"> amy1</a>
    </li>
    <li>
        <a href = "img/amy-2.jpg" onclick="showPic(this);return false;" title = "amy2"> amy2</a>
    </li>
    <li>
        <a href = "img/amy-3.jpg" onclick="showPic(this);return false;" title = "amy3"> amy3</a>
    </li>
    <li>
        <a href = "img/amy-4.jpg" onclick="showPic(this);return false;" title = "amy4"> amy4</a>
    </li>
    <img id="placeholder" src="img/test.jpg" alt="my image gallery" />
</ul>
<script type="text/javascript" src="scripts/shoWPic.js"></script>

js代码

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

把js代码里第三行document.getElementById("placeholder")换成document.getElementsByTagName("img")
阅读 3.6k
评论
    4 个回答
    • 37

    document.getElementsByTagName("img")返回的是document中标签名为img的合集,如果你想换需要写为document.getElementsByTagName("img")[0]

      相似问题
      推荐文章