事件類型對照表
| 事件 | 觸發時機 | 是否冒泡 | 適用場景 |
| focus | 獲得焦點 | 否 | 顯示提示、啟用編輯狀態 |
| blur | 失去焦點 | 否 | 驗證、保存、隱藏提示 |
| change | 值改變並失焦(select/radio/checkbox 即時) | 是 | 表單提交前最終驗證 |
| input | 值實時改輸(輸入、粘貼、拖拽、自動填充) | 是 | 實時搜索、字數統計、格式化 |
| keydown/keypress/keyup | 鍵盤按下/輸入字符/抬起 | 是 | 鍵盤快捷鍵、輸入攔截 |
| propertychange | IE 專屬,屬性改變時觸發 | 是 | 舊 IE 兼容 input 事件 |
正確綁定寫法
// 推薦:on() 統一綁定,支持動態元素
$('#myInput')
.on('focus', function() {
$(this).addClass('focused');
showHint(this);
})
.on('blur', function() {
$(this).removeClass('focused');
validateField(this);
hideHint();
})
.on('input', function() {
// 實時字數統計
var len = this.value.length;
$('#char-count').text(len + '/200');
// 實時格式化(如自動添加空格)
if (this.dataset.format === 'card') {
this.value = this.value.replace(/\s/g, '').replace(/(\d{4})/g, '$1 ').trim();
}
})
.on('change', function() {
// 失焦後最終確認
if (this.value !== this.defaultValue) {
markAsDirty(this);
}
});
change vs input 關鍵差異
<input id="test" type="text">
$('#test')
.on('input', function() { console.log('input:', this.value); })
.on('change', function() { console.log('change:', this.value); });
// 用戶操作流程:
// 1. 聚焦輸入 "a" → 觸發 input("a")
// 2. 繼續輸入 "b" → 觸發 input("ab")
// 3. 點擊其他地方失焦 → 觸發 change("ab")
// 4. 直接粘貼 "xyz" → 觸發 input("xyz"),失焦觸發 change("xyz")
// 5. 使用瀏覽器自動填充 → 僅觸發 input(部分瀏覽器不觸發 change)
舊 IE 兼容方案
// IE9- 不支持 input 事件,需用 propertychange
var eventName = 'oninput' in document.createElement('input') ? 'input' : 'propertychange';
$('#myInput').on(eventName, function(e) {
// propertyChange 事件對象無 e.target,需用 e.srcElement
var target = e.target || e.srcElement;
console.log(target.value);
});
動態元素事件委託
// 父容器委託,適用於後添加的 input
$('#form-container').on('input', 'input[data-auto-format]', function() {
var $this = $(this);
var fmt = $this.data('auto-format');
if (fmt === 'uppercase') {
$this.val($this.val().toUpperCase());
} else if (fmt === 'number') {
$this.val($this.val().replace(/\D/g, ''));
}
});
常見坑點
- change 不觸發: JS 代碼修改
val() 不觸發 change,需手動 .trigger('change')
- focus/blur 不冒泡: 不能用委託,需用
focusin/focusout(冒泡版)
- 中文輸入法: 組字過程中
input 會頻繁觸發,compositionstart/end 配合過濾
- 自動填充: 瀏覽器自動填充可能只觸發
input 不觸發 change,驗證邏輯要兼容
中文輸入法完美處理
var composing = false;
$('#search-input')
.on('compositionstart', function() { composing = true; })
.on('compositionend', function(e) {
composing = false;
// 組字結束後手動觸發一次 input 邏輯
handleInput(e.target.value);
})
.on('input', function(e) {
if (!composing) handleInput(e.target.value);
});
function handleInput(val) {
// 實時搜索建議等邏輯
debounceSearch(val);
}