我通常使用 Java 编写代码,但我了解一点 HTML,所以我决定学习更多内容。我的问题是我有一个 password field
和一个 submit
按钮。当我按下按钮时,它会检查密码是否正确,然后询问您的名字是什么。然后,它将文本字段更改为 You got it right, NAME
。问题是,当您点击“提交”时,提交的代码将添加到 URL 中,因此如果您输入 password
作为密码,?password
添加到 URL 中。这对我来说没问题,但由于 URL 发生了更改,页面会重新加载,从而使文本字段恢复正常。我正在使用谷歌浏览器。无论如何,是否有这个问题,或者是因为我正在运行 .HTML 文件,而不是访问网站?
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<title>Ryan Club Homepage</title>
<script>
function codeEnter(){
var s = document.getElementById("in").value;
var correct = "lolliPiper5";
if(s === correct){
var name = prompt("What is your name");
document.getElementById("cde").innerHTML = "You got the password right!, " + name;
}
}
</script>
</head>
<body style="font-family:'Myriad Pro' ">
<form onsubmit="codeEnter();">
<input type="password" name="code" id="in">
<br />
<input type="submit" value="Ready!">
</form>
</body>
</html>
谢谢!
最佳答案
您需要使用JavaScript/jQuery来阻止表单提交。我正在使用jQuery 2.1.1。
对于密码字段,我们暂时假设它为123。
e.preventDefault() 方法阻止元素的默认操作发生。此处它会停止提交按钮,将表单提交到表单的 action 属性中指定的 URL。
$(document).ready(function(){
$("#name_container").hide();
$('#submit').on("click",function(e){
e.preventDefault();
$password = $('#password').val();
if($password == '123'){
$("#password_container").hide();
$("#name_container").show();
$("#result").html("");
}
else{
$("#result").html("Password is incorrect.");
}
$name = $("#name").val();
if($name != '' && $name != null ){
$("#form").hide();
$("#result").html("You got it right, "+$name);
}
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="page.html" method="post" id="form">
<div id="password_container">
Password: <input type="password" id="password" />
</div>
<div id="name_container">
Name: <input type="text" id="name" />
</div>
<input type="submit" id="submit">
</form>
<div id="result">
</div>
(已更新) 给你:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body style="font-family:'Myriad Pro' ">
<form id="form" method="post" action="#">
Password:
<input type="password" name="code" id="in">
<br />
<input type="submit" value="Ready!" id="submit">
</form>
<div class="ps"></div>
<script>
$(document).ready(function () {
$('#submit').on("click", function (e) {
e.preventDefault();
$password = $('#in').val();
if ($password == 'lolliPiper5') {
$name = prompt("Enter your name", "ACCESS GRANTED");
$(".ps").html("Welcome to the team, " + $name);
}
});
});
</script>
</body>
</html>
关于javascript - .HTML 文件的 URL 中有密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38276964/