#javascript #html #events #modal-dialog
#javascript #HTML #Мероприятия #модальный диалог
Вопрос:
Я изменил HTML-пример W3, который отображает модальные диалоги, добавив дополнительные кнопки в первую модальную форму. Есть два способа выйти из модального, нажав на фон и используя кнопку выхода. Другие кнопки предназначены для функций формы и не должны приводить к закрытию формы. У меня две проблемы:
- все кнопки приводят к закрытию формы, даже если выполнение не переходит к строке кода, которая скрывает модальную форму. что-то не так с
if(event.target.className == "modal") { event.target.style.display = "none"; } }```
обработчик, который закрывает форму, даже если она не проходит if
условие.
2. При выходе из диалога с помощью кнопки выхода строка URL родительской страницы обновляется, чтобы включить последний ответ JASON от сервера: http://127.0.0.1:20080/?jason=/api/cage/poweramp;name={ «data»: [ { «status»: 1 }, { «status»: 1 } ] } или добавляется с помощью http://127.0.0.1:20080 /**?джейсон=amp;имя=**
если не было вызова на сервер
Я пытался отладить проблемы, пройдя по коду, но не смог найти причину или исправить обе проблемы, возникающие из кода скрипта, любая помощь будет принята с благодарностью.
Мой код:
<html> <head>
<title>Title of the document</title>
<style> * {font-family: Arial !important;}</style>
<style>
.modal {
display: none;
position: fixed;
z-index: 8;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgb(0, 0, 0);
background-color: rgba(0, 0, 0, 0.4);
}
.modal-content {
margin: 50px auto;
border: 1px solid #999;
width: 700px;
}
h2,p {
margin: 0 0 20px;
font-weight: 400;
color: #000;
}
span {
color: #666;
display: block;
padding: 0 0 5px;
}
form {
padding: 0px;
margin: 0px;
box-shadow: 0 2px 5px #f5f5f5;
background: #fff;
}
input, textarea {
width: 90%;
padding: 10px;
margin-bottom: 20px;
border: 1px solid #1c87c9;
outline: none;
}
.contact-form button {
width: 100%;
padding: 10px;
border: none;
background: #09253d;
font-size: 16px;
font-weight: 400;
color: #fff;
}
button:hover {
background: #0A354d;
}
.close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover, .close:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
button.modalButton {
background: none;
border-top: none;
outline: none;
border-right: none;
border-left: none;
border-bottom: #02274a 1px solid;
padding: 0 0 3px 0;
font-size: 16px;
cursor: pointer;
}
button.modalButton:hover {
border-bottom: #a99567 1px solid;
color: #a99567;
}
.column {
float: left;
width: 200px;
padding: 0px;
height: 100px;
}
.row:after {
/* Clear floats after the columns */
content: "";
display: table;
clear: both;
}
</style>
<style> table, td { outline: 0;border: 1px solid #000; } </style>
</head>
<body>
<h2>Multiple Popup Forms</h2>
<p>
<button id="module0" class="modalButton" data-modal="modalOne">Contact Us</button>
</p>
<p>
<button id="module2" class="modalButton" data-modal="modalTwo">Send a Form</button>
</p>
<div id="modalOne" class="modal">
<div class="modal-content">
<div class="contact-form">
<!--a class="close">amp;times;</a-->
<form action="/">
<div class="row" float="left" background="#fa7a25">
<div class="column" style="width:30px; height:60px; background: #fa7a25">
<div class="column" style="width:8px; margin-left:16px; margin-top:10px; height:36px; border:1px solid #000; background: #00dd00"></div>
</div>
<div class="column" style="width:480px; height:60px; background: #fa7a25">
<div style="height:10px;"></div>
<a style="color:#fff; font-size: 18px;margin-left:8px; ">S/N: Serial Number line</a>
<p><a style="color:#fff; margin-left:8px;height:14px;"> information line</a></p>
</div>
<div class="column" style="width:190px; height:60px; background: #eee"></div>
</div>
<div class="row" float="left" background="#fa7a25">
<div class="column" style="width:510px; height:300px; background: #fff">
<div style="height:10px;"></div>
<div class="column" style="height:20px;margin-left:12px;width:100px;">
<b>Get REST:</b>
</div>
<div class="column" style="height:30px;margin-left:12px;width:100px;">
<select id="jason" name="jason" onclick="myChange()">
<option></option>
<option>/api/cage</option>
<option>/api/cage/state</option>
<option>/api/cage/power</option>
<option>/api/cage/groups</option>
</select>
</div>
<div>
<input id="input1" style="margin-left:12px;" class="fname" type="text" name="name" placeholder="Full name">
</div>
<span style="margin-left:12px;">Message</span>
<div>
<textarea style="margin-left:12px;"rows="4"></textarea>
</div>
</div>
<div class="column" style="width:190px; height:300px; background: #eee">
<button id="save-default" style="margin-top:12px;">Save as Default</button>
<button id="restore-factory" style="margin-top:30px;">Restore Factory</button>
<button id="quitButton" type="cancel" href="/" style="margin-top:80px;">Quit</button>
</div>
</div>
</form>
</div>
</div>
</div>
<div id="modalTwo" class="modal">
<div class="modal-content">
<div class="contact-form">
<span class="close">amp;times;</span>
<form action="/">
<h2>My form</h2>
<div>
<input class="fname" type="text" name="name" placeholder="Full name">
<input type="text" name="name" placeholder="Email">
<input type="text" name="name" placeholder="Phone number">
</div>
<span>Message</span>
<div>
<textarea rows="4"></textarea>
</div>
<button id="quitButton" type="cancel" href="/">Quit</button>
</form>
</div>
</div>
</div>
<script>
modalBtns = [...document.querySelectorAll(".modalButton")];
modalBtns.forEach( function(btn) {
// setup dialog opening buttons for the modal dialogs
if (btn.getAttribute('data-modal')) {
btn.addEventListener('click', function() {
modal = btn.getAttribute('data-modal');
if (modal) {
document.getElementById(modal).style.display = "block";
}});
}
else if (btn.type == 'cancel') {
btn.addEventListener('click', function() {
// Form cancel button closes the dialog box
if (btn.type == 'cancel') {
modal = btn.closest('.modal');
modal.style.display = "none";
// console.log(window.location.href );
}});
}
});
window.onclick = function(event) {
if(event.target.className == "modal") {
event.target.style.display = "none";
}
}
function myChange() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
if (this.readyState == 4 amp;amp; this.status == 200) {
var myObj = JSON.parse(this.responseText);
if (document.getElementById('jason').value == "/api/cage/state")
document.getElementById("input1").value = "State is: " myObj.data;
else if (document.getElementById('jason').value == "/api/cage")
document.getElementById("input1").value = myObj.data.partNumber;
else
document.getElementById("input1").value = this.responseText
}
};
xhttp.open("GET", document.getElementById('jason').value, true);
xhttp.send();
}
</script>
Ответ №1:
После публикации вопросов я обнаружил, что кнопка HTML имеет поведение по умолчанию, которое задается свойством type кнопки. Если оставить его неустановленным, по умолчанию используется значение submit, что позволяет JS браузера делать свое дело. чтобы исправить обе проблемы, я просто изменил тип всех кнопок на кнопку.