迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

在 JavaScript 的警报框中显示变量值

作者:迹忆客 最近更新:2024/03/18 浏览次数:

在本文中,我们将学习在 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 变量的成功消息。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

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 选择器的不同方法。你还将找到许多有用的

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便