这是我的代码示例。概要是这样的:
用户在电子邮件字段中输入电子邮件地址。
用户单击“提交”按钮。
出现一个警告框,“电子邮件地址已添加到数据库!”显示。
用户在该警报框中单击“确定”。
“提交”按钮变为“已提交!”。
用户单击“已提交!”按钮。
警报框显示“您已经提交了电子邮件地址!”显示。
最后一步,显示了另一个警报框,这是我遇到问题的地方。
<!DOCTYPE html>
<html>
<head>
<title>This is the code used to create a field and submit button.</title>
</head>
<body>
<!--The below code is creating a field and submit button-->
<label id= "email_field_text" for="email_field"> Input your email to subscribe to funny comics and memes by yours truly</label>
<input id="email_field" type="email" placeholder="---> Enter Your Email Here <---">
<input type="Submit" Id="emailsubmitbutton" style="background-color: green" value="Submit" onClick= "myfunction()" required="required">
<!--The below code is changing the Submit" button to "Submitted!" once clicked and also showing an alert box.-->
<script>
function myfunction() {
document.getElementById("emailsubmitbutton").value= "Submitted!";
alert("Email address has been added to database!");
}
//Code in this space will display an alert box once a user clicks the "Submittted!" button. The alert box will display the following string: "You have already submitted your email address!".-->
</script>
</body>
</html>
最佳答案
Mr Geek is right在用户已提交电子邮件之后,应使用if
语句运行其他alert
语句。
但是,与其检查DOM节点(页面的HTML元素的表示形式)以查看程序的状态,不如将状态存储在变量中。在您的情况下,您可以存储一个布尔变量hasSubmitted
,该变量最初是false
,但在用户提交电子邮件时将其设置为true
。
<!DOCTYPE html>
<html>
<head>
<title>This is the code used to create a field and submit button.</title>
</head>
<body>
<!--The below code is creating a field and submit button-->
<label id="email_field_text" for="email_field"> Input your email to subscribe to funny comics and memes by yours truly</label>
<input id="email_field" type="email" placeholder="---> Enter Your Email Here <---">
<input type="Submit" Id="emailsubmitbutton" style="background-color: green" value="Submit" onClick="myfunction()" required="required">
<!--The below code is changing the Submit" button to "Submitted!" once clicked and also showing an alert box.-->
<script>
var hasSubmittedYet = false;
function myfunction() {
var submitButton = document.getElementById("emailsubmitbutton");
if (!hasSubmittedYet) {
submitButton.value = "Submitted!";
hasSubmittedYet = true;
alert("Email address has been added to database!");
} else {
alert("You have already submitted your email address!");
}
}
</script>
</body>
</html>
顺便说一句,您可以通过在提交电子邮件后禁用电子邮件地址
input
来改善界面,以明确您在提交电子邮件后无法更改它:var emailField = document.getElementById("email_field");
emailField.disabled = true;
那将在
true
的第一个分支(if (!hasSubmittedYet) {
分支)中进行。关于javascript - 仅在输入按钮的值更改后,使用JavaScript和jQuery更改警报框中的字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50590974/