使用事件解释弹出消息?

我们可以使用弹出框向应用程序用户显示弹出消息。我们将在本教程中了解不同类型的 JavaScript 弹出框。
下面的 JavaScript 中提供了三种不同类型的弹出框。
警报框
确认框
提示框
下面我们将一一了解所有的弹出框。
警报框
我们可以使用 window.alert() 方法显示警报框。它只是在弹出框中显示消息。
当我们需要向用户提供一些消息时,我们可以使用警报框。例如,当用户登录应用程序时,它会显示类似“您登录成功”的消息。
语法
用户可以按照以下语法在 JavaScript 中显示警报框。
alert(message)
参数
消息- 这是一条显示在警报框中的消息。
示例
在此示例中,当用户单击按钮时,我们将调用 showAlert() 函数。 showAlert() 函数使用alert() 方法来显示警报框。
在输出中,用户可以观察到,当我们按下按钮时,它会显示警报框,其中消息作为参数传递。当我们按下警报框中的“确定”按钮时,它就会消失。
<html>
<body>
<h2> Showing the alert message using the <i> alert box. </i> </h2>
<button onclick = "showAlert()"> Show Alert Message </button>
</body>
<script>
// function to show alert
function showAlert() {
alert("This is the important message");
}
</script>
</html>
确认框
当我们需要用户确认时,我们可以使用确认框。例如,在删除一些重要数据之前,我们需要得到用户的确认。
我们可以使用 window.confirm() 方法显示确认框。确认框包含两个按钮,其中包含文本“确定”和“取消”。如果用户按下取消按钮,则返回 false;否则为真。
语法
用户可以按照以下语法在 JavaScript 中显示确认框。
confirm(message);
参数
消息- 这是一条显示在确认框中的确认消息。
返回值
它根据用户是否按下“确定”或“取消”按钮返回 true 和 false 布尔值。
示例
在这个例子中,我们使用了window对象的confirm()方法来显示确认框。此外,根据用户按下确认框的“确定”或“取消”按钮,我们会在屏幕上向用户显示不同的消息。
<html>
<body>
<h2> Showing the confirm box using the <i> confirm() </i> method.</h2>
<p id = "output"> </p>
<button onclick = "showConfirm()"> Show Confirm box </button>
</body>
<script>
let message = "Kindly confirm once by pressing the ok or cancel button!";
// function to show confirm box
function showConfirm() {
// showing the confirm box with the message parameter
let returnValue = confirm(message);
let output = document.getElementById("output");
// According to the returned boolean value, show the output
if (returnValue) {
output.innerHTML += "You pressed the ok button.";
} else {
output.innerHTML += "You pressed the cancel button.";
}
}
</script>
</html>
提示框
提示框是 JavaScript 中显示弹出消息的第三种方式。提示框是alert()和确认框的高级版本。它在框中显示消息并接受用户的输入。此外,它还包含用于提交输入值的确定和取消按钮。
语法
用户可以按照以下语法使用提示框在 JavaScript 中获取用户输入。
prompt(message, placeholder);
我们在上面的语法中调用了静态prompt()方法。
参数
message - 这是一条显示在输入框上方的消息。
占位符- 这是在输入框中显示的文本。
返回值
如果用户按下确定按钮,则返回输入值;否则为空。
示例
在此示例中,我们创建了 takeInput() 函数,该函数向用户显示提示框。我们使用提示框来获取用户输入的名称。
当用户输入输入值后按下确定按钮时,我们会在屏幕上显示用户的输入。
<html>
<body>
<h2> Showing the prompt box using the <i> prompt() </i> method. </h2>
<p id = "output"> </p>
<button onclick = "takeInput()"> Show Prompt box </button>
</body>
<script>
let message = "Enter your name";
// function to take input using the prompt box
function takeInput() {
// showing the prompt with the message parameter
let returnValue = prompt(message, "Shubham");
let output = document.getElementById("output");
if (returnValue) {
output.innerHTML += "Your good name is " + returnValue;
} else {
output.innerHTML +=
"You pressed the cancel button, or you entered the null value";
}
}
</script>
</html>
我们已经通过本教程中的示例了解了所有三种不同的弹出框。如果我们只需要显示消息,我们可以使用警告框,如果我们只需要用户确认,我们应该使用确认框。如果我们需要输入值或在弹出框中确认某个值,我们应该使用提示框。
javascript