萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 文本框事件處理:即時偵測、Enter 鍵提交、焦點控制

一、即時偵測輸入變化:propertychange / input

change 事件需失去焦點才觸發,無法即時響應。跨瀏覽器方案:

// IE 專屬 propertychange,現代瀏覽器用 input 事件
$('#flowfromid').on('input propertychange', function() {
    // 此處處理即時邏輯,如字數統計、即時搜尋
    console.log('值已變更:', this.value);
});

二、Enter 鍵觸發提交

$(document).ready(function() {
    $('#txt_JumpPager').on('keydown', function(e) {
        if (e.which === 13) { // 13 = Enter
            $('#lbtn_JumpPager').trigger('click');
            return false; // 防止表單預設提交
        }
    });
});

三、焦點控制實用片段

1. 頁面載入自動聚焦

$('#txtEmail').trigger('focus');

2. 焦點進入/離開切換樣式

$(function() {
    $(':input').on('focus', function() {
        $(this).addClass('focus');
    }).on('blur', function() {
        $(this).removeClass('focus');
    });
});

配合 CSS:

.focus { border-color: #4a90e2; box-shadow: 0 0 4px rgba(74,144,226,0.4); }

四、事件對照表

需求推薦事件備註
即時偵測輸入input (現代) / propertychange (IE≤11)合併寫 on('input propertychange')
失去焦點後驗證change / blurchange 僅值改變時觸發
Enter 鍵提交keydown 判斷 e.which===13勿用 keypress(已棄用)
獲得焦點focus / focusin (冒泡)focusin 可委派
失去焦點blur / focusout (冒泡)focusout 可委派

五、常見坑點提醒

  • propertychange 僅 IE 支援,現代專案請優先用 input,並配合 $.support 或直接雙綁。
  • 在 keydown 中 return false 等同 e.preventDefault() + e.stopPropagation()。
  • 動態新增的輸入框需用事件委派:$(document).on('input', '.dynamic-input', fn)。
copyright © 萬盛學電腦網 all rights reserved