在 HTML 標籤的內聯事件屬性裡寫 this,它代表的就是「目前這個標籤元素本身」。這讓我們不必用 id 查詢,就能直接把元素交給函數處理。
<html>
<head>
<script type="text/javascript">
function showHint(str) {
alert(str);
}
</script>
</head>
<body>
<input type="text" onkeyup="showHint(this.value)" />
</body>
</html>
執行結果:在文字框中輸入字元並放開按鍵(觸發 keyup)後,會跳出剛才輸入的字元。
這裡的 this.value 就等於 document.getElementById(...).value,只是省下了取元素的步驟。同理,this.style.color='red'、this.disabled=true 這些常見寫法都是在操作當前元素。
<!-- 改變自身樣式 -->
<button onmouseover="this.style.backgroundPosition='left -36px'"
onmouseout="this.style.backgroundPosition='left top'">按鈕</button>
<!-- 把自身傳給函數 -->
<select onchange="showHint(this.options[this.selectedIndex].value)">
<option value="1">一</option>
</select>
<!-- 操作群組中的兄弟元素 -->
<div onclick="this.style.display='none'">點我消失</div>
要注意的是,this 的指向取決於「函數是怎麼被呼叫的」,而非定義位置。在內聯事件屬性中,瀏覽器會把 this 綁定為該元素;但若把 this 傳進另一個函數後再於別處使用,它仍會指向原元素(因為是作為參數傳值)。反之,若在一般函數或 setTimeout 的箭頭函數外層使用 this,指向就會變成 window 或其他物件,這也是許多 this 相關 bug 的來源。