在 JavaScript 的警报框中显示变量值
在本文中,我们将学习在 JavaScript 中使用 alert()
方法。我们将学习如何使用警告框在网页上向用户显示一条消息或任何其他有用的信息作为弹出窗口。
在 JavaScript 的警报框中显示变量值
要在弹出窗口中显示任何值,我们必须使用警告框。默认情况下,它包含用于隐藏和关闭弹出对话框的 OK
按钮。
当用户与网页交互时,大多数时候,开发人员需要借助警报框向用户传达有用的信息。例如,当用户从客户端将数据上传到服务器时,网页在验证后会在弹出对话框中显示成功或失败消息。
警报框将用户的焦点从活动网页上移开,迫使用户阅读警报消息。
在 JavaScript 中,默认的 alert()
方法可以在连接运算符 +
的帮助下显示警报消息、变量值和文本以及变量。
基本语法:
let data = 'hello world'
alert(data);
如上所示,我们只需要将值或变量作为参数传递给 alert()
方法。
例子:
<html>
<head>
<title> display JavaScript alert </title>
</head>
<script>
function showPopup()
{
var data = document.getElementById("value").value;
//check empty data field
if(data == "")
{
alert("Please enter any value..");
}
else
{
alert("Your entered value is: "+data); //display variable along with the string
}
}
</script>
<body>
<h1 style="color:blueviolet">DelftStack</h1>
<h3>JavaScript display alert box</h3>
<form onsubmit ="return showPopup()">
<!-- data input -->
<td> Enter Value: </td>
<input id = "value" value = "">
<br><br>
<input type = "submit" value = "Submit">
</form>
</body>
</html>
我们使用上述 HTML 源代码中的 form
元素来创建用户输入字段和 Submit
按钮。用户将插入一个值,当用户单击 Submit
按钮时,将触发函数 showPopup()
。
在脚本标签中,我们声明了 showPopup()
函数,我们在 data
变量中获取用户输入值并使用条件语句 if
检查 data
是否为空。
如果 data
变量为空,它将显示带有错误消息的警报。否则,它将显示带有 data
变量的成功消息。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
用 jQuery 检查复选框是否被选中
发布时间:2024/03/24 浏览次数:102 分类:JavaScript
-
在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。