它的JS与HTML标签是分离的吗

一个单的利用JS切换图片的功能
它的JS与HTML标签是分离的吗
写法1:

  <section>
      <h2>JS切换图片</h2>
      <ul class="pictable">
        <li><a href="img/1.jpg" onclick="showPic(this);return false" title="this picture is beautiful"><img class="picbox" src="img/1.jpg" alt=""></a></li>
        <li><a href="img/2.jpg" onclick="showPic(this);return false" title="this picture is beautiful"><img class="picbox" src="img/2.jpg" alt=""></a></li>
        <li><a href="img/3.jpg" onclick="showPic(this);return false" title="this picture is beautiful"><img class="picbox" src="img/3.jpg" alt=""></a></li>
        <li><a href="img/4.jpg" onclick="showPic(this);return false" title="this picture is beautiful"><img class="picbox" src="img/4.jpg" alt=""></a></li>
    </ul>
    <p id="pic_description">图片描述</p>
    <img src="https://b-ssl.duitang.com/uploads/item/201408/04/20140804204624_xSeGA.png" id="placeholder" alt="img fult">
    </section>
    
      function showPic(whichpic){
      //改变图片
    var source =  whichpic.getAttribute("href");
    var placeholder=document.getElementById("placeholder");
    placeholder.setAttribute("src",source);
    //改变图片描述
    function showPic_description(){
      var text=whichpic.getAttribute("title");
      var pic_desciption=document.getElementById("pic_desciption");
      pic_desciption.childNodes[0].nodeValue=text;
    };
  };

写法2:

<section>
      <h2>JS切换图片</h2>
      <ul class="pictable" id="img_gallert">
        <li><a href="img/1.jpg"  title="this picture is beautiful"><img class="picbox" src="img/1.jpg" alt=""></a></li>
        <li><a href="img/2.jpg"  title="this picture is beautiful"><img class="picbox" src="img/2.jpg" alt=""></a></li>
        <li><a href="img/3.jpg"  title="this picture is beautiful"><img class="picbox" src="img/3.jpg" alt=""></a></li>
        <li><a href="img/4.jpg"  title="this picture is beautiful"><img class="picbox" src="img/4.jpg" alt=""></a></li>
    </ul>
    <p id="pic_description">图片描述</p>
    <img src="https://b-ssl.duitang.com/uploads/item/201408/04/20140804204624_xSeGA.png" id="placeholder" alt="img fult">
    </section>
    
    window.onload=prepareGallery;
function prepareGallery(){
  //找到图片集
  var gallery=document.getElementById("img_gallert");
  // 图片集的a元素节点
  var link=gallery.getElementsByTagName("a");
  // 遍历节点
  for(var i=0;i<link.length;i++){
    link[i].onclick=function(){
        showPic(this);
        return false;
    }
  }
};
function showPic(whichpic){
    //改变图片
  var source =  whichpic.getAttribute("href");
  var placeholder=document.getElementById("placeholder");
  placeholder.setAttribute("src",source);
};

虽然功能都一样,但是写法2却更好JS不会因为HTML里的代码改变了,就导致无法执行。
好的JS应该与HTML标签是分离的。后期维护更加方便

上一篇:Python 多张图片合成视频


下一篇:淡入淡出轮播