2017-04-11 50 views
0

我在開始學習Javascript。我希望你能幫助我。用class代替id顯示fancybox

我想使用fancybox,如果有人點擊一個類屬性的鏈接。我也用id來完成它。使用id屬性代碼工作得很好。但是,如果我帶班cange它的屬性它doesn't工作.... :(

<!-- Trigger/Open The Modal --> 
<button id="myBtn">Open Modal</button> 

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

    <!-- Modal content --> 
    <div class="modal-content"> 
    <span class="close">&times;</span> 
    <p>Some text in the Modal..</p> 
    </div> 

</div> 

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

// Get the button that opens the modal 
var btn = document.getElementById("myBtn"); 

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

// When the user clicks the button, open the modal 
btn.onclick = function() { 
    modal.style.display = "block"; 
} 

// When the user clicks on <span> (x), close the modal 
span.onclick = function() { 
    modal.style.display = "none"; 
} 

// When the user clicks anywhere outside of the modal, close it 
window.onclick = function(event) { 
    if (event.target == modal) { 
     modal.style.display = "none"; 
    } 
} 
</script> 

此代碼的工作很細,但爲什麼鴕鳥政策工作這一項,只有類屬性?代碼也紛紛在相同的元素上一個,只有代碼以下行已被更改。

<button class="myBtnNew">Open Modal New</button> 

var myBtnNew = document.getElementsByClassName("myBtnNew"); 

myBtnNew.onclick = function() { 
    modal.style.display = "block"; 
} 

謝謝您的幫助...

回答

0

getElementsBy,因爲它說,resturns多個元素,一個列表。所以myBtnNew是元素列表,列表中沒有onclick,因此只需添加[0]就可以了span:

var myBtnNew = document.getElementsByClassName("myBtnNew")[0]; 
0

document.getElementsByClassName返回一個對象數組,而不僅僅是一個對象。使用這個:

var myBtns = document.getElementsByClassName("myBtnNew"); 

myBtns[0].onclick = function() { 
    modal.style.display = "block"; 
} 
+0

非常感謝。它很好用。:) –