2016-10-03 37 views
0

我剛剛遵循w3school教程這個bootstrap模態圖像。我的頁面中有兩張圖像卡。所以我需要彈出這兩個圖像。但它只能處理一張圖片。Bootstrap模式圖像不工作 - 多

Link to w3school article

<!-- Trigger the Modal --> 

<img id="myImg" src="http://d14dsi4x2zx6ql.cloudfront.net/files/styles/welcome_image/public/VCW_TI_5_BayLoop_Hero_Manley_1280x642_sized.jpg?itok=EaARDZt8" alt=""> 

<!-- The Modal --> 
<div id="myModal" class="modal"> 

    <!-- The Close Button --> 
    <span class="close" onclick="document.getElementById('myModal').style.display='none'">&times;</span> 

    <!-- Modal Content (The Image) --> 
    <img class="modal-content" id="img01"> 

    <!-- Modal Caption (Image Text) --> 
    <div id="caption"></div> 
</div> 

我插入我的其他形象 「myImg」 標識,但沒有奏效。第一個圖像彈出如我所料。這裏會缺少什麼?

+0

您不能在頁面上的多個元素上使用相同的ID,因爲它們是唯一的。但是,如果有幫助,您可以使用多個類。 – Lee

+0

爲什麼這個問題有'boo'標籤? – Headcrab

回答

1

你不能給兩個要素相同的ID 如果你想要做兩個相同的動作,你可以給他們班

<img class="myImg" src="http://placehold.it/850x450" alt="image1" width="200"> 
<img class="myImg" src="http://placehold.it/700x400/f00" alt="image2" width="200"> 

和JS將是:

// Get the modal 
var modal = document.getElementById('myModal'); 

// Get the image and insert it inside the modal - use its "alt" text as a caption 
var img = document.getElementsByClassName('myImg'); 
var modalImg = document.getElementById("img01"); 
var captionText = document.getElementById("caption"); 
//iterate over img to add click event for each one,, jquery will make it much easier 
for(var i=0;i< img.length;i++){ 
    img[i].onclick = function(){ 
     modal.style.display = "block"; 
     modalImg.src = this.src; 
     captionText.innerHTML = this.alt; 
    } 
} 

//jquery option 
/*$('.myImg').on('click', function(){ 
    modal.style.display = "block"; 
    modalImg.src = $(this).attr('src'); 
    captionText.innerHTML = $(this).attr('alt'); 
})*/ 

// Get the <span> element that closes the modal 
var span = document.getElementsByClassName("close")[0]; 

Demo

+0

Omg!我只是忘了HTML的基礎。謝謝! – Janath