prompt() 是瀏覽器原生對話框 API,雖然 UI 簡陋且會阻塞主執行緒,但在簡單互動、除錯、原型驗證場合仍有使用價值。本文完整說明回傳值特性、型別陷阱與最佳實務。
var result = prompt(message, defaultValue);
| 使用者操作 | 回傳值 | 型別 |
|---|---|---|
| 輸入文字並按「確定」 | 輸入的字串 | String |
| 不輸入直接按「確定」 | 預設值 (第二參數) 或空字串 | String |
| 按「取消」或關閉視窗 | null | Null |
| 按 ESC 鍵 | null | Null |
var input = prompt("請輸入數字", "123");
console.log(typeof input); // "string" - 即使輸入純數字
// 必須手動轉型
var num = Number(input); // 或 parseInt(input, 10)
var num2 = +input; // 快速轉數字
var num3 = parseFloat(input); // 浮點數
<script>
var password = prompt("請輸入密碼", "");
if (password === null) {
console.log("使用者取消輸入");
} else if (password === "admin") {
document.write("密碼正確");
} else {
document.write("密碼錯誤");
}
</script>
注意:使用 === 嚴格比較,避免 "" == null 為 true 的隱性轉換陷阱。
| 方法 | 用途 | 回傳值 | 阻塞主執行緒 |
|---|---|---|---|
alert(msg) | 單向通知 | undefined | 是 |
confirm(msg) | 是/否確認 | Boolean (true/false) | 是 |
prompt(msg, default) | 文字輸入 | String / null | 是 |
原生 prompt() 缺點:
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
Swal.fire({
title: '請輸入密碼',
input: 'password',
inputPlaceholder: '輸入密碼',
showCancelButton: true,
confirmButtonText: '確認',
cancelButtonText: '取消',
inputValidator: (value) => {
if (!value) return '請輸入密碼!';
}
}).then((result) => {
if (result.isConfirmed) {
if (result.value === 'admin') {
Swal.fire('密碼正確!', '', 'success');
} else {
Swal.fire('密碼錯誤!', '', 'error');
}
}
});
function customPrompt(message, defaultValue = '') {
return new Promise((resolve) => {
// 建立 modal 結構
var overlay = document.createElement('div');
overlay.className = 'prompt-overlay';
overlay.innerHTML = `
<div class="prompt-box">
<p>${message}</p>
<input type="text" value="${defaultValue}" autofocus>
<div class="btn-group">
<button class="btn-ok">確定</button>
<button class="btn-cancel">取消</button>
</div>
</div>
`;
var input = overlay.querySelector('input');
var okBtn = overlay.querySelector('.btn-ok');
var cancelBtn = overlay.querySelector('.btn-cancel');
okBtn.onclick = () => { resolve(input.value); cleanup(); };
cancelBtn.onclick = () => { resolve(null); cleanup(); };
overlay.onclick = (e) => { if (e.target === overlay) { resolve(null); cleanup(); } };
function cleanup() {
document.body.removeChild(overlay);
input.focus(); // 歸還焦點
}
document.body.appendChild(overlay);
input.focus();
input.select();
});
}
// 使用:async/await 風格
async function demo() {
var pwd = await customPrompt('請輸入密碼');
if (pwd === 'admin') alert('正確');
else if (pwd !== null) alert('錯誤');
else alert('已取消');
}
type="password" 效果)<input type="password"> + 後端雜湊驗證prompt() 回傳字串或 null,記得轉型與嚴格比較。教學、除錯、內部工具可用;面向使用者的正式功能請改用自訂 Modal 或成熟 UI 庫,兼顧體驗與安全。