JavaScript的弹窗有三种——警告框、确认框和提示框

1.alert()--警告框

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

语法:alert("sometext");\window.alert("sometext");

注意:

          (1)本方法返回值是undefined

          (2)alert()方法弹出的对话框是模态对话框

              在对话框关闭之前程序暂停,直到关闭后继续执行

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>js弹窗</title>
	</head>
	<body>
		<button>alert()警告框</button>
	</body>
	<script type="text/javascript">
		document.querySelectorAll("button")[0].onclick = function(){
			var result = alert("这是一个警告框");
			console.log(result); //undefined
		};
	</script>
</html>

2.confirm()--确认框

描述:确认框通常用于验证是否接受用户操作

语法:confirm("sometest");\window.confirm("sometext");

注意:

          (1)点击确定按钮返回true,取消按钮返回false

          (2)confirm()方法弹出的对话框是模态对话框

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>js弹窗</title>
	</head>
	<body>
		<button>confirm()确认框</button>
	</body>
	<script type="text/javascript">
		document.querySelectorAll("button")[0].onclick = function(){
			var result = confirm("这是一个确认框?");
			console.log(result); 
		};
	</script>
</html>

3.prompt()--提示框

描述:提示框经常用于提示用户进入页面前输入某个值

语法:prompt("sometext","defaultvalue");\window.prompt("sometext","defaultvalue");

注意:

          (1)如果直接点击取消,则返回null

          (2)如果由默认值并直接点击确定,则返回默认值。如果输入内容则返回输入的内容

          (3)如果没有默认值并直接点击确定,则返回空字符串。如果输入内容则返回输入的内容

          (4)prompt()方法弹出的对话框是模态对话框,在对话框关闭之前程序暂停,直到关闭才能继续执行

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>js弹窗</title>
	</head>
	<body>
		<button>prompt()提示框</button>
	</body>
	<script type="text/javascript">
		document.querySelectorAll("button")[0].onclick = function(){
			var result = prompt("几天几号?","1");
			console.log(result);
		};
	</script>
</html>

拓展:

弹窗使用反斜杠+n(\n)来设置换行

alert("hello\n hello world!");
confirm("hello\n hello world!");
prompt("hello\n hello world!");

 

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐