Contributor 無意間發現 window.prompt() 這個方法,之前一直沒用過。有些時候我們不只想知道使用者「按了確定還是取消」,還需要他們輸入一點內容,這時 prompt() 就能派上用場。
var result = window.prompt(message, default);
message:顯示在對話框中的提示文字。default:輸入框的預設值(可省略)。null。<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script>
var _saytext = "我真笨";
var err_list = new Array("別亂填!!", "快填,別試了!!");
var _text = prompt("在下面輸入框填「" + _saytext + "」");
for (var i = 0; _text != _saytext; ++i) {
if (i == err_list.length) i = 0;
alert(err_list[i]);
_text = prompt("在下面輸入框填「" + _saytext + "」");
}
alert("嗯,這就對了!");
</script>
</head>
</html>
這個範例示範了 prompt 最典型的用法:反覆詢問直到得到滿意的答案為止。原範例用 decodeURI("我真笨") 來處理編碼,現在直接寫中文字串即可,頁面宣告 UTF-8 就不會有亂碼問題。
alert(message):只有一個「確定」按鈕,回傳 undefined。confirm(message):確定/取消,回傳 true 或 false。prompt(message, default):可輸入文字,回傳字串或 null。三者都是同步且模態的:對話框顯示期間,整個頁面的 JavaScript 執行會暫停,直到使用者回應。這也是它們最大的問題。
<dialog id="myDialog">
<form method="dialog">
<label>請輸入:<input id="userInput" type="text"></label>
<button value="cancel">取消</button>
<button value="confirm">確定</button>
</form>
</dialog>
<script>
const dlg = document.getElementById('myDialog');
document.getElementById('openBtn').onclick = () => dlg.showModal();
dlg.addEventListener('close', function() {
if (dlg.returnValue === 'confirm') {
console.log(document.getElementById('userInput').value);
}
});
</script>
<dialog> 可以用 CSS 完整客製、支援鍵盤操作與焦點管理,是目前的首選。
若要欄位驗證、多個輸入、自訂按鈕,可考慮 SweetAlert2 這類函式庫,API 簡潔且外觀現代。
例如寫內部工具、除錯用的小腳本,那 prompt 的便利性確實無可取代。請至少記住:
null(使用者按了取消),否則後續程式碼會拿到 null 而炸掉。var name = prompt('請輸入姓名');
if (name === null) {
return; // 使用者取消了
}
name = name.trim();
if (name === '') {
alert('名稱不可為空');
return;
}