[英]Buttons are opening the same modal
我在頁面上使用2模態。 我用一個按鈕打開這些模式:
<button type="button" id="myBtn1">Modal 1</button>
<button type="button" id="myBtn2">Modal 2</button>
當我單擊按鈕時,按鈕將打開相同的模式。 我該如何解決?
這是模態
方式1:
<div id="myModal1" class="modal">
<div class="modal-content">
<span class="close">×</span>
<div class="row">
<div class="">
<div class="x_content">
<p>content modal 1</p>
</div>
</div>
</div>
</div>
</div>
模態2:
<div id="myModal2" class="modal">
<div class="modal-content">
<span class="close">×</span>
<div class="row">
<div class="">
<div class="x_content">
<p>content modal 2</p>
</div>
</div>
</div>
</div>
</div>
腳本模式1:
<script>
// Get the modal
var modal = document.getElementById('myModal1');
// Get the button that opens the modal
var btn = document.getElementById("myBtn1");
// 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>
腳本模式2:
<script>
// Get the modal
var modal = document.getElementById('myModal2');
// Get the button that opens the modal
var btn = document.getElementById("myBtn2");
// 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>
你應該把私有功能
(function(){
// Get the modal
var modal = document.getElementById('myModal2');
// Get the button that opens the modal
var btn = document.getElementById("myBtn2");
// Get the <span> element that closes the modal
var span = modal.getElementsByClassName("close")[0];//<<<<pay attention here
...
}());
您最好實際上是每個btn.onclick
分配元素。 您正在調用全局變量modal,它將使用最近分配的值。
// for first script
btn.onclick = function() {
document.getElementById("myModal1").style.display = "block";
}
// for second script
btn.onclick = function() {
document.getElementById("myModal2").style.display = "block";
}
不要為modal和btn使用相同的名稱。
嘗試
// Get the modal
var modal1 = document.getElementById('myModal1');
// Get the button that opens the modal
var btn1 = document.getElementById("myBtn1");
// Get the modal
var modal2 = document.getElementById('myModal2');
// Get the button that opens the modal
var btn2 = document.getElementById("myBtn2");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.