Window alert() 方法
实例
显示一个弹出框:
<!DOCTYPE html><html><body><p>单击按钮以显示 alert 消息框。</p><button onclick="myFunction()">试一试</button><script>function myFunction() {alert("Hello! I am an alert box!");}</script></body></html>
定义与用法
alert() 方法显示带有指定消息和确定按钮的消息框。
如果您想确保信息传达给用户,通常会使用 alert 警告消息框 。
注意:消息框将焦点从当前窗口移开,并强制浏览器读取消息。不要过度使用此方法,因为它会阻止用户在关闭框之前访问页面的其他部分。
浏览器支持
| 方法 | |||||
|---|---|---|---|---|---|
| alert() | Yes | Yes | Yes | Yes | Yes |
语法
alert(message)
参数值
| 参数 | 类型 | 描述 |
|---|---|---|
| message | String | 可选。 指定要在提示框中显示的文本,或指定转换为字符串并显示的对象 |
技术细节
| 返回值: | 无返回值 |
|---|
更多实例
实例
带换行符的警告消息框:
<!DOCTYPE html><html><body><p>单击按钮以演示警告消息框中的换行符。</p><button onclick="myFunction()">试一试</button><script>function myFunction() {alert("Hello\nHow are you?");}</script></body></html>
实例
警告当前 URL 的主机名:
<!DOCTYPE html><html><body><p>单击该按钮以警告当前 URL 的主机名。</p><button onclick="myFunction()">试一试</button><script>function myFunction() {alert(location.hostname);}</script></body></html>
相关页面
Window 对象: confirm()方法
Window 对象: prompt()方法