JavaScript 消息框

本文介绍了JavaScript中常用的三种消息框:警告框、确认框和提示框。详细解释了每种消息框的功能、使用场景及语法,并提供了示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

可以在 JavaScript 中创建三种消息框:警告框、确认框、提示框。

警告框

警告框经常用于确保用户可以得到某些信息。

当警告框出现后,用户需要点击确定按钮才能继续进行操作。

语法:

alert("文本")
案例:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>

<body>
<input type="button" onclick="disp_alert()" value="显示警告框" />
<script>

function disp_alert()
{
alert("我是警告框!!")
}
</script>
</body>
</html>
效果图:


带有折行的警告框

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>

<body>
<input type="button" onclick="disp_alert()" value="显示警告框" />

<script type="text/javascript">
function disp_alert()
{
alert("再次向您问好!在这里,我们向您演示" + '\n' + "如何向警告框添加折行。")
}
</script>

</body>
</html>
效果图:

确认框

确认框用于使用户可以验证或者接受某些信息。

当确认框出现后,用户需要点击确定或者取消按钮才能继续进行操作。

如果用户点击确认,那么返回值为 true。如果用户点击取消,那么返回值为 false。

语法:

confirm("文本")
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>

<body>

<input type="button" onclick="disp_alert()" value="显示警告框" />
<br />

<input type="button" onclick="show_confirm()" value="Show a confirm box" />
<script>
	function show_confirm(){
		var r = confirm("Press a button!");
		if(r == true){
			alert("OK!");
		}else{
			alert("Cancel!");
		}	
	}
</script>

</body>
</html>
效果图:

提示框

提示框经常用于提示用户在进入页面前输入某个值。

当提示框出现后,用户需要输入某个值,然后点击确认或取消按钮才能继续操纵。

如果用户点击确认,那么返回值为输入的值。如果用户点击取消,那么返回值为 null。

语法:

prompt("文本","默认值")
案例:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>

<body>

<input type="button" onclick="disp_prompt()" value="显示提示框" />
<script>
	function disp_prompt(){
		var name = prompt("请输入名字","name");
		if(name != null && name != ""){
			document.write("您好!" + name + "祝您每天开心!");
		}	
	}
</script>

</body>
</html>
效果图:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值