需實時監聽 <input id="Search"> 的輸入值,初始代碼:
$('#Search').bind('input propertychange', function () {
alert($("input[name=Search]").value); // 錯誤:jQuery 對象無 value 屬性
});
$("input[name=Search]") 返回 jQuery 對象,需用 .val() 或 [0].value 取值。this 在事件處理器中指向原生 DOM 元素,直接用 this.value 最簡潔。$('#Search').on('input propertychange', function () {
// this 為原生 input 元素
console.log(this.value); // 實時值
// 或 $(this).val()
});
| 事件 | 觸發時機 | 支持瀏覽器 |
|---|---|---|
input | 值發生變化(輸入、刪除、粘貼、拖拽) | IE9+, Firefox, Chrome, Safari, Edge |
propertychange | IE 專有,元素屬性變化 | IE6-IE11 |
keydown/keyup | 按鍵按下/釋放 | 所有,但無法捕捉鼠標粘貼、拖拽、IME 輸入 |
input + Polyfill現代項目建議僅監聽 input,IE9+ 原生支持;若需兼容 IE8,引入 jquery-legacy 或自行補丁:
// 簡易 IE8 補丁
if (!('oninput' in document.createElement('input'))) {
$(document).on('propertychange', 'input,textarea', function(e) {
if (e.originalEvent.propertyName === 'value') {
$(this).trigger('input');
}
});
}