第一篇筆記,從最基礎的 DOM 操作開始:取值、驗證、寫回頁面。
點擊 show 按鈕時觸發 showValue(),把 input 的值動態寫進 id="text" 的元素裡。
<p>
<input type="text" value="" name="user_name" id="user_name" />
<span style="padding-left:10px;"><input type="button" value="show" onclick="showValue()" /></span>
</p>
<p id="text"></p>
讓輸入框自動取得焦點,引導使用者直接開始輸入。這是個便宜又有效、卻常被忽略的使用者體驗細節。
window.onload = function(){
var user_name = document.getElementById("user_name");
user_name.focus();
}
若完全沒有輸入內容,給出錯誤提示並把焦點拉回輸入框:
function showValue(){
var user_name = document.getElementById("user_name");
var text = document.getElementById("text");
if(user_name.value == ""){
alert("Please input some words");
user_name.focus();
}else{
text.innerHTML = user_name.value;
text.setAttribute("class", "text");
}
}
HTML 裡那個 <div id="text"></div> 其實可以不寫,改用 DOM 即時建立並掛進文件:
// 建立 div 元素
var text = document.createElement("div");
// 把 user_name.value 的內容放進 div
text.appendChild(user_name.value);
// 最後把 div 掛到 body 下
document.body.appendChild(text);
createElement 與 appendChild 這一對組合,是所有動態 DOM 操作的地基。理解它之後,你才會真正明白 jQuery 的 append()、html() 這些方法背後在忙什麼。
上面 appendChild 那一行其實是錯的。appendChild 的參數必須是一個節點(Node),而 user_name.value 是一個字串。把字串傳進去會丟出 TypeError。
正確的寫法有兩種。若內容只是純文字,用 textContent:
text.textContent = user_name.value;
若要建立文字節點再掛上去,則是:
text.appendChild(document.createTextNode(user_name.value));
這個錯誤剛好點出了本文最重要的一條觀念:innerHTML 與 textContent 的選擇。
前面 showValue() 裡用的 text.innerHTML = user_name.value 看似正常,但 innerHTML 會把字串當成 HTML 解析。也就是說,使用者在輸入框裡打 <img src=x onerror=alert(1)>,這段標籤就會真的被執行——這是最典型的 XSS(跨站腳本攻擊)寫法。
規則很簡單:只要內容是使用者輸入或任何來路不明的資料,一律用 textContent;只有內容是你自己寫死的、可信的 HTML 片段,才用 innerHTML。這條習慣從第一行程式碼就該養成,之後會替你擋掉大量安全問題。
附帶一提,text.setAttribute("class", "text") 若元素已有其他 class,會把它們全部蓋掉。改用 text.classList.add("text") 更安全。