如果要确保信息传递给用户,通常会使用警告框。
当警告框弹出时,用户将需要单击“确定”来继续。
window.alert("sometext");
window.alert() 方法可以不带 window 前缀来写。
alert("我是一个警告框!");
<!doctype html>
<html>
<body>
<h1>javascript 警告框</h1>
<button onclick="myfunction()">试一试</button>
<script>
function myfunction() {
alert("我是一个警告框!");
}
</script>
</body>
</html>
如果您希望用户验证或接受某个东西,则通常使用“确认”框。
当确认框弹出时,用户将不得不单击“确定”或“取消”来继续进行。
如果用户单击“确定”,该框返回 true。如果用户单击“取消”,该框返回 false。
window.confirm("sometext");
window.confirm() 方法可以不带 window 前缀来编写。
var r = confirm("请按按钮"); if (r == true) { x = "您按了确认!"; } else { x = "您按了取消!"; }
<!doctype html>
<html>
<body>
<h1>javascript 确认框</h1>
<button onclick="myfunction()">试一试</button>
<p id="demo"></p>
<script>
function myfunction() {
var txt;
if (confirm("press a button!")) {
txt = "您按了确定";
} else {
txt = "您按了取消";
}
document.getelementbyid("demo").innerhtml = txt;
}
</script>
</body>
</html>
如果您希望用户在进入页面前输入值,通常会使用提示框。
当提示框弹出时,用户将不得不输入值后单击“确定”或点击“取消”来继续进行。
如果用户单击“确定”,该框返回输入值。如果用户单击“取消”,该框返回 null。
window.prompt("sometext","defaulttext");
window.prompt() 方法可以不带 window 前缀来编写。
var person = prompt("请输入您的姓名", "比尔盖茨"); if (person != null) { document.getelementbyid("demo").innerhtml = "你好 " + person + "!今天过的怎么样?"; }
<!doctype html>
<html>
<body>
<h1>javascript prompt</h1>
<button onclick="myfunction()">试一试</button>
<p id="demo"></p>
<script>
function myfunction() {
var txt;
var person = prompt("请输入您的名字:", "哈利波特");
if (person == null || person == "") {
txt = "用户取消输入";
} else {
txt = "你好," + person + "!今天过得好吗?";
}
document.getelementbyid("demo").innerhtml = txt;
}
</script>
</body>
</html>
如需在弹出框中显示折行,请在反斜杠后面加一个字符 n。
alert("hello\nhow are you?");
<!doctype html>
<html>
<body>
<h1>javascript</h1>
<p>在警告框中换行。</p>
<button onclick="alert('hello\nhow are you?')">试一试</button>
</body>
</html>
如对本文有疑问, 点击进行留言回复!!
网友评论