JavaScript 弹出框


目录

    显示目录


JavaScript 共有三种弹出框:警告框、确认框和提示框。


警报箱

如果您想确保信息传达给用户,通常会使用警报框。

当弹出警告框时,用户必须单击“确定”才能继续。

句法

window.alert("sometext");

window.alert()方法可以不用window来编写 字首。

例子

自己尝试一下 →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Alert</h2>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
  alert("I am an alert box!");
}
</script>

</body>
</html>

确认框

如果您希望用户验证或接受某些内容,通常会使用确认框。

当弹出确认框时,用户必须单击“确定”或“取消”才能继续。

如果用户单击“确定”,则该框返回true。如果用户单击“取消”,则该框返回

句法

window.confirm("sometext");

window.confirm() 方法可以不带 window 前缀。

例子

自己尝试一下 →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Confirm Box</h2>


<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
  var txt;
  if (confirm("Press a button!")) {
    txt = "You pressed OK!";
  } else {
    txt = "You pressed Cancel!";
  }
  document.getElementById("demo").innerHTML = txt;
}
</script>

</body>
</html>


提示框

如果您希望用户在进入页面之前输入一个值,通常会使用提示框。

当弹出提示框时,用户必须单击“确定”或“取消” 输入输入值后继续。

如果用户单击“确定”,该框将返回输入值。如果用户单击“取消”,该框将返回 null。

句法

window.prompt("sometext","defaultText");

window.prompt() 方法可以不带 window 前缀编写。

例子

自己尝试一下 →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Prompt</h2>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
  let text;
  let person = prompt("Please enter your name:", "Harry Potter");
  if (person == null || person == "") {
    text = "User cancelled the prompt.";
  } else {
    text = "Hello " + person + "! How are you today?";
  }
  document.getElementById("demo").innerHTML = text;
}
</script>

</body>
</html>

换行符

要在弹出框中显示换行符,请使用反斜杠后跟字符 n。

例子

自己尝试一下 →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript</h2>
<p>Line-breaks in a popup box.</p>

<button onclick="alert('Hello\nHow are you?')">Try it</button>

</body>
</html>