2016-04-26 30 views
1

我有一個快速問題,我需要幫助,並希望一組新的眼睛可以查明我的問題。我有一個照片庫,我想在點擊時顯示縮略圖的大圖。縮略圖圖像在底部顯示正常,但不可點擊,主要(或較大圖像)不顯示。我正在使用外部.js文件。我也會上傳HTML,也許有人可以指引我正確的方向,並幫助我理解我所忽視的內容。JS相冊。獲取大圖像顯示和縮略圖可點擊

<!doctype html> 

<html> 


<head> 
    <title>Photo Gallery Final Project</title> 
    <meta charset = "UTF-8"> 
    <link rel = "stylesheet" href = "gallery.css"> 


</head> 

<body> 

    <div class = "main"> 

     <div class = "wrapper"> 

      <div id = "largeImage"> 

     <img src = "images/machine_1_big.jpg" alt = "machining image" width = "920" height = "400" id = "myImage" class = "border"/> 

      </div> 

      <div class = "thumbnail"> 

       <img src="machine_1.jpg" alt = "machining lathe" id="machine_1"/> 
       <img src="machine_2.jpg" alt = "machining lathe" id="machine_2"/> 
       <img src="machine_3.jpg" alt = "machining lathe" id="machine_3"/> 
       <img src="machine_4.jpg" alt = "machining lathe" id="machine_4"/> 
       <img src="machine_5.jpg" alt = "machining lathe" id="machine_5"/> 
       <img src="machine_6.jpg" alt = "machining lathe" id="machine_6"/> 

      </div> 
     </div> 
    </div> 

    <script src = "gallery.js"></script> 


</body> 




</html> 

//this will load the gallery in the browser and enable the gallery function 
//window.onload = gallery; 
//gallery funtion declared 
function gallery(){ 
    //variable allGalleryImages created. This is where all the images will be held 
    var allGalleryImages = document.images; 
    //for loop declared for the image array 
    for(var i = 0; i < allGalleryImages.length; i++){ 
      if(allGalleryImages[i].id.indexOf("small") > -1){ 
       //this will add a listener to the thumb images 
       allGalleryImages[i].onclick = imgChanger; 

      } 
    } 
} 
//this is the image changer function 
function imgChanger(){ 
    //this will change the src attribute value of the large image. 
    //document.getElementById('myImage').src ="images/"+this.id+"_big.jpg"; 
     document.getElementById('myImage').src = " " + this.id +"_big.jpg"; 

} 
+0

你用JQuery好嗎? – theblindprophet

+0

當然。繼續前進並拍攝。 – Murk

回答

0

我用JQuery。不必改變你的HTML。沒有理由製作和排列所有的縮略圖。

$(document).ready(function() { 
    $(".thumbnail img").on("click", function() { 
     imgChanger($(this).attr("src")); 
    }) 


    //this is the image changer function 
    function imgChanger(theSRC) { 
     //this will change the src attribute value of the large image. 
     //document.getElementById('myImage').src ="images/"+this.id+"_big.jpg"; 
     var beforeJPG = theSRC; 
     console.log(beforeJPG); 
     beforeJPG = beforeJPG.substring(0, beforeJPG.length-4); 
     console.log(beforeJPG + "_big.jpg"); 
     $("myImage").attr("src", beforeJPG + "_big.jpg"); 
    } 
}) 

小提琴:https://jsfiddle.net/6v8arhp2/

  1. 獲取點擊的圖像
  2. 砍掉的 「jpg」
  3. 添加 「圖像/」 到前面的src,加上 「_big.jpg」到後面
  4. 更改src的#myImage

**當然,您的圖像不在JSFiddle內部,因此您無法看到它的工作,但控制檯日誌顯示轉換。