我一直在尝试验证Modal窗口中的密码文本。当我输入不正确的密码时,警报将继续显示“ Login iscorrect”消息。似乎我正在使用的while循环,一直在继续。如何使警报消息仅显示一次。但是“模态”窗口应继续显示
var modal = document.getElementById('loginModal');
// Get the button that opens the modal
var btn = document.getElementById("loginBtn");
// 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";
}
function promptPassword( )
{
while (document.getElementById("pwdText").value != 'P@ssw0rd'){
alert("Login is incorrect");
document.getElementById('pwdText').value = "";
}
alert("Password is correct, you are allowed to enter the site");
}
.modal {
display: none; /* Modal not shown by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
padding-top: 100px; /* Location of the modal box */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
}
/* Modal Content */
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 25%;
height: 25%;
}
/*Display of text box labels*/
label{
display: inline-block;
float: left;
clear: left;
width: 250px;
text-align: left;
}
label {
display: inline-block;
float: left;
}
/*Display of text and password boxes*/
input[type=text] {
width:250px;
}
input[type=password] {
width:250px;
}
/* Close Button */
.close {
float: right;
margin: -15px -15px 0 0;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
text-decoration: none;
cursor: pointer;
}
<!-- Login button to pen Modal box -->
<button id="loginBtn">Login</button>
<!-- The Modal box-->
<div id="loginModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<form>
<br/>
<label>User Name</label><input id="userName" type="text"><br />
<br/>
<label>Password</label><input id="pwdText" type="password"><br />
<br/>
<button onclick="promptPassword()">Submit</button>
</form>
</div>
我需要在不使用Jquery的情况下执行此操作
最佳答案
首先,您需要更换
<button onclick="promptPassword()">Submit</button>
至
<button onclick="return promptPassword()">Submit</button>
那你只需要用这个
function promptPassword( )
{
var pwd = document.getElementById("pwdText").value;
if(pwd != 'P@ssw0rd'){
alert("Login is incorrect");
document.getElementById('pwdText').value = "";
return false;
}
else{
alert("Password is correct, you are allowed to enter the site");
// Enter Site Code Here
}
}
关于javascript - 即使我使用Java单击“确定”后,错误密码的警报也会继续显示。如何停止连续显示警报消息,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40904446/