我在頁面上使用2個模態。我用一個按鈕打開這些模式:按鈕打開相同的模式
<button type="button" id="myBtn1">Modal 1</button>
<button type="button" id="myBtn2">Modal 2</button>
當我點擊按鈕時,按鈕打開相同的模式。我該如何解決這個問題?
這裏是模態
Modal1:
<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>
Modal2:
<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>
你是如何加載這些腳本?將第二個模態的變量名稱從「var modal」更改爲var modal2 – karthick
,因爲您始終調用的'modal'將是您分配的最新的模型,可能是'myModal2' –
@karthick更改變量名稱工作。謝謝 – John