JavaScript 的基礎可以拆成幾個區塊:輸出、變數、DOM、表單、視窗、字串、日期與事件。掌握這些區塊,就能處理大部分網頁互動需求。
document.write("Hello");
var name = "Hege";
console.log(name);
document.write 會把內容寫入文件,console.log 則常用於除錯。變數宣告可使用 var,現代寫法也常用 let 與 const。
var el = document.getElementById("output");
el.value = el.value.toUpperCase();
DOM 是網頁元素的物件模型。透過 getElementById、querySelector 等方法取得元素後,就能修改文字、樣式、屬性與內容。
表單元素可透過 document.forms、elements、checked、selectedIndex 等屬性處理。例如判斷核取方塊是否勾選、取得下拉選單選取值、清空文字欄位。
常見視窗方法包括 window.open、window.close、alert、confirm、prompt。時間處理則常用 setTimeout、setInterval、clearTimeout 與 clearInterval。
字串常用方法包括 length、indexOf、charAt、substring、split、replace、toUpperCase、toLowerCase。日期物件則可用 new Date 建立,並以 getFullYear、getMonth、getDate 取得年月日。
事件包括 onclick、onload、onchange、onSubmit 等。錯誤處理可使用 try...catch,讓程式在異常時有較友善的反應。
這些觀念彼此相扣,理解之後就能開始製作表單驗證、動態內容、倒數計時、彈出提示與小型應用。