本章整理 JavaScript 與使用者互動的基礎做法,包括輸出、警告、確認、輸入、跳轉、分支與例外處理。
document.write 可以直接輸出內容,但在頁面載入後使用可能覆蓋文件,因此實務上多改用 DOM 操作。
alert("廣州百匯物流有限公司");
if (confirm("是否訪問我們的首頁")) {
alert("是的,前往");
} else {
alert("退出");
}
var ans = prompt("輸入你的留言", "您好,");
if (ans) {
alert("你說:" + ans);
} else {
alert("退出,沒有留言");
}
window.location = "index.html";
可透過 switch 判斷不同 id 的按鈕,再顯示對應訊息。
var ans = prompt("輸入參數:", "");
try {
if (!ans || isNaN(ans)) {
throw new Error("輸入為非數");
}
alert("根號 " + ans + " 是 " + Math.sqrt(ans));
} catch (errMsg) {
alert(errMsg.message);
}
try 與 catch 能讓程式在發生錯誤時,以較友善的方式提示使用者。