gpt4 book ai didi

javascript - 仅在输入按钮的值更改后,使用 JavaScript 和 jQuery 更改警报框中的字符串

转载 作者:行者123 更新时间:2023-11-28 14:33:37 26 4
gpt4 key购买 nike

这是我的代码示例。概要是这样的:

  1. 用户在电子邮件字段中输入电子邮件地址。
  2. 用户点击“提交”按钮。
  3. 警告框显示“电子邮件地址已添加到数据库!”显示。
  4. 用户在该警告框中点击“确定”。
  5. “提交”按钮更改为“已提交!”。
  6. 用户点击“已提交!”按钮。
  7. 警告框显示“您已经提交了您的电子邮件地址!”显示。

最后一步,显示不同的警报框,是我遇到麻烦的地方。

<!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 元素的表示)来查看程序状态相比,将状态存储在变量中会更干净。在您的情况下,您可以存储一个 bool 变量 hasSubscribed,该变量最初为 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>

顺便说一句,您可以通过在提交电子邮件后禁用电子邮件地址输入来改进界面,以明确您在提交电子邮件后无法更改电子邮件:

var emailField = document.getElementById("email_field");
emailField.disabled = true;

这将进入 if (!hasSubscribedYet) { 的第一个分支(true 分支)。

关于javascript - 仅在输入按钮的值更改后,使用 JavaScript 和 jQuery 更改警报框中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50590974/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com