confirm()方法用於顯示帶有可選消息和兩個按鈕(確定和取消)的模式對話框。如果用戶單擊“OK”,則返回true,否則返回false。在框關閉之前,它可以防止用戶訪問頁麵的其他部分。
用法:
confirm(message)
message是要在對話框中顯示的可選字符串。
它返回一個布爾值,指示是選擇“確定”還是“取消”(true表示OK,false表示用戶單擊“ cancel”)。
示例1:
<!DOCTYPE html>
<html>
<head>
<title>
Window confirm() Method
</title>
</head>
<body style="text-align:center;">
<h1 style="color:green;">
GeeksforGeeks
</h1>
<h2>
Window confirm() Method
</h2>
<p>Click the button to display a confirm box.</p>
<button onclick="geek()">Click me!</button>
<script>
function geek() {
confirm("Press OK to close this option");
}
</script>
</body>
</html>
輸出:
在單擊按鈕之前:
單擊按鈕後:
示例2:
<!DOCTYPE html>
<html>
<head>
<title>
Window confirm() Method
</title>
</head>
<body style="text-align:center;">
<h1 style="color:green;">
GeeksforGeeks
</h1>
<h2>
Window confirm() Method
</h2>
<button onclick="geek()">Click me!</button>
<p id="g"></p>
<script>
function geek() {
var doc;
var result = confirm("Press a button!");
if (result == true) {
doc = "OK was pressed.";
} else {
doc = "Cancel was pressed.";
}
document.getElementById("g").innerHTML = doc;
}
</script>
</body>
</html>
輸出:
在單擊按鈕之前:
單擊按鈕後:
支持的瀏覽器:下麵列出了窗口confirm()方法支持的瀏覽器:
- 穀歌瀏覽器
- IE瀏覽器
- 火狐瀏覽器
- Opera
- 蘋果瀏覽器
相關用法
- Javascript Window print()用法及代碼示例
- Javascript Window getComputedStyle()用法及代碼示例
- Javascript Window scrollTo()用法及代碼示例
- Javascript Window prompt()用法及代碼示例
注:本文由純淨天空篩選整理自Vishal Chaudhary 2大神的英文原創作品 Javascript | Window confirm() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。