2016-10-03 4 views
0

방금 ​​부트 스랩 모달 이미지에 대한 w3school 튜토리얼을 따랐습니다. 내 페이지에는 두 개의 이미지 카드가 있습니다. 그래서 두 개의 이미지를 팝업해야합니다. 그러나 하나의 이미지로만 작동합니다.부트 스트랩 모달 이미지가 작동하지 않음 - 복수

<!-- 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"ID 삽입

Link to w3school article

, 그러나 그것은 작동하지 않았다. 첫 번째 이미지 팝업이 예상대로 작동했습니다. 무엇이 여기에서 놓칠 것입니까?

+0

고유 한 ID는 페이지의 둘 이상의 요소에서 사용할 수 없습니다. 그러나 도움이된다면 여러 클래스를 사용할 수 있습니다. – Lee

+0

이 질문에 'boo' 태그가있는 이유는 무엇입니까? – Headcrab

답변

1

당신이 클래스

<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가 될 것입니다 그들에게 줄 수있는 모두에 대해 동일한 작업을 수행하려는 경우 당신은 두 가지 요소에 동일한 ID 를 제공 할 수 없습니다

// 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

관련 문제