の
var modal = document.getElementById('myModal_1');
var btn = document.getElementById("modal_1");
var span = document.getElementsByClassName("close")[0];
btn.onclick = function() {
modal.style.display = "block";
}
span.onclick = function() {
modal.style.display = "none";
}
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
コンテンツ下のJSFiddleのリンクは、問題は、あなたがあなた自身の変数を上書きしていることです。
あなたは、両方のイベントハンドラのためvars
modal
、btn
、およびspan
を使用しています。モーダル2は後で設定されるので、そのボタンの値はmodal
です。
また、document.getElementsByClassName("close")[0]
は最初close
クラス要素に両方のイベントハンドラは、あなたが独自の変数を使用する必要がモーダル1.
を隠そうとしているので、X
がmodal 2
上で動作しない理由であるたびに、取得します名前が同じ範囲内にある場合は、document.getElementsByClassName
のような文書レベルのコマンドは常に先頭から始まることに注意してください。
また、window.onclick
を2回割り当て、2番目の値を最初に上書きします。
ここでは、必要な機能を得るための最小限の編集をすばやく取り上げますが、ここで使用するよりも変数の命名法を考えてみましょう。
// Get the modal
var modal = document.getElementById('myModal_1');
// Get the button that opens the modal
var btn = document.getElementById("modal_1");
// 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";
}
// Get the modal
var modal2 = document.getElementById('myModal_2');
// Get the button that opens the modal
var btn2 = document.getElementById("modal_2");
// Get the <span> element that closes the modal
var span2 = document.getElementsByClassName("close")[1];
// When the user clicks the button, open the modal
btn2.onclick = function() {
modal2.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span2.onclick = function() {
modal2.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal || event.target == modal2) {
event.target.style.display = "none";
}
}
JSFiddleが私にとってうまくいくようです。予期しない動作は何ですか? – Goose
モーダル1は「モーダル1」を開き、モーダル2は「モーダル2」を開きます。各リンクは「モーダル2」を開きます。私は命名法を更新してより意味をなさないようにしました。 –
私はJSFiddleで1つのモーダルしか見ることができません。 '#modal_planting_mix'。 JSFiddleを確認し、更新してください。 – Goose