2017-06-01 15 views
0

私は自分のページに2つのモーダルを使用しています。ボタンでこれらのモーダルを開きます:ボタンが同じモーダルを開く

<button type="button" id="myBtn1">Modal 1</button> 
<button type="button" id="myBtn2">Modal 2</button> 

ボタンをクリックすると、ボタンが同じモーダルを開きます。どうすれば修正できますか?

0123:モーダル1

<div id="myModal2" class="modal"> 
    <div class="modal-content"> 
    <span class="close">&times;</span> 
    <div class="row"> 
     <div class=""> 
     <div class="x_content">     
      <p>content modal 2</p> 
     </div> 
     </div> 
    </div> 
    </div> 
</div> 

スクリプト:

<div id="myModal1" class="modal"> 
    <div class="modal-content"> 
    <span class="close">&times;</span> 
    <div class="row"> 
     <div class=""> 
     <div class="x_content">     
      <p>content modal 1</p> 
     </div> 
     </div> 
    </div> 
    </div> 
</div> 

Modal2:ここ

Modal1モーダルです

スクリプトモーダル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> 
+1

を試してみてください? 2番目のモーダルの変数名を "var modal"から "var modal2 – karthick

+0

"に変更してください。あなたが常に呼び出しているモーダルは、あなたが割り当てた最新のものになります。おそらく 'myModal2' –

+0

@karthick変更された変数名が機能しました。ありがとう – John

答えて

0

プライベート関数を入れて、モーダルとBTNに同じ名前のVaRいけないはずです。

はどのようにこれらのスクリプトをロードしている

// 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"); 
0

あなたが実際にbtn.onclickあたりの要素を割り当てる方がいいでしょう。最後に割り当てられた値を使用するグローバル変数モーダルを呼び出しています。

// for first script 
btn.onclick = function() { 
    document.getElementById("myModal1").style.display = "block"; 
} 


// for second script 
btn.onclick = function() { 
    document.getElementById("myModal2").style.display = "block"; 
} 
1

あなたは

(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 
    ... 
}()); 
関連する問題