原代碼僅在 click 事件中使用 this.value,實際上任何能觸發處理函數的事件 (如 mouseover、focus、change) 都能獲取 this.value。
| 事件 | 觸發時機 | 典型用途 |
|---|---|---|
click | 滑鼠點擊釋放 | 按鈕提交、切換顯示 |
mouseover / mouseenter | 滑鼠移入元素 | 懸停提示、預覽 |
focus | 元素獲得焦點 | 輸入框提示、驗證 |
change | 值改變並失去焦點 | <select>、<input> 修改確認 |
input | 值實時改變 | 即時搜索、字數統計 |
keydown/keyup | 鍵盤按下/釋放 | 快捷鍵、輸入過濾 |
<input type="text" id="txt" value="初始值" />
<div id="show"></div>
<script>
document.getElementById('txt').onmouseover = function() {
document.getElementById('show').innerText = '當前值: ' + this.value;
};
</script>
$('#txt').on('mouseover focus input', function() {
$('#show').text('值: ' + this.value); // this 指向原生 DOM 元素
});
// 或使用事件對象
$('#txt').on('input', function(e) {
console.log(e.target.value); // 更規範
});
this 在內聯處理函數 (onxxx) 和 addEventListener 回調中指向觸發事件的 DOM 元素。e.target 或 e.currentTarget。value 屬性對 input、select、textarea、button 等表單元素均有效。選擇合適事件,this.value 即可在 click 之外靈活使用。