表單交互是前端高頻場景。jQuery 封裝了統一、跨瀏覽器的表單操作 API,但版本差異(如 @ 選擇器已棄用)導致舊代碼失效。本文基于 jQuery 3.x+ 現代語法,系統梳理 Select、Radio、Checkbox、Text 等元素的獲取、設置、動態操作、事件綁定全場景方案。
@ 屬性前綴)
// ❌ 舊版 (jQuery < 1.8)
$('input[@name="sex"][@checked]')
// ✅ 現代 (jQuery 1.8+)
$('input[name="sex"]:checked')
$('select[name="country"] option:selected')
const $sel = $('#selectId');
// 值 (value 屬性)
const val = $sel.val(); // 單選
const vals = $sel.val(); // 多選返回數組
// 文本
const text = $sel.find('option:selected').text(); // 單選
const texts = $sel.find('option:selected').map((_,o)=>o.text).get(); // 多選
// 索引
const idx = $sel.prop('selectedIndex'); // 0-based
const maxIdx = $sel.find('option').length - 1;
// 按值
$sel.val('targetValue'); // 單選
$sel.val(['val1', 'val2']); // 多選
// 按索引
$sel.prop('selectedIndex', 1); // 第二項
// 按文本 (需遍歷)
$sel.find('option').filter((_,o) => o.text === '目標文本').prop('selected', true);
// 追加
$sel.append('');
// 前置
$sel.prepend('');
// 批量構建 (性能優於循環 append)
const items = ['幼兒園','小學','初中','高中','大學'];
const html = items.map((t,i) => ``).join('');
$sel.empty().append(html).val('0'); // 默認首項
// 刪除
$sel.find('option:last').remove(); // 最後
$sel.find('option[value="3"]').remove(); // 指定值
$sel.find('option[index="0"]').remove(); // 指定索引 (屬性選擇器)
$sel.find('option:contains("文本")').remove(); // 指定文本
$sel.on('change', function() {
const $this = $(this);
console.log('值:', $this.val());
console.log('文本:', $this.find('option:selected').text());
console.log('索引:', $this.prop('selectedIndex'));
});
// 現代寫法
const val = $('input[name="sex"]:checked').val();
// 兼容無選中情況
const val = $('input[name="sex"]:checked').val() ?? '未選擇';
// 按值
$('input[name="sex"][value="female"]').prop('checked', true);
// 按索引 (原生 DOM)
$('input[name="sex"]').get(1).checked = true; // 第二個
// 遍歷匹配 (原文模式)
const targetVal = 'female';
$('input[name="sex"]').each(function() {
this.checked = this.value === targetVal;
});
// 單個 checkbox
const checked = $('#chk1').prop('checked'); // true/false
const val = $('#chk1').val(); // 值
// 多個同名 checkbox (值數組)
const vals = $('input[name="items"]:checked').map((_,el)=>el.value).get();
// 或
const vals = $('input[name="items"]:checked').val(); // 僅返回第一個值,慎用
// 勾選
$('#chk1').prop('checked', true);
// 取消
$('#chk1').prop('checked', false);
// 切換
$('#chk1').prop('checked', function(i, v) { return !v; });
// 批量設置
$('input[name="items"]').prop('checked', true); // 全選
$('input[name="items"][value="1"], [value="3"]').prop('checked', true); // 指定值
if ($('#chk1').prop('checked')) { ... } // 推薦 prop
if ($('#chk1').is(':checked')) { ... } // 也可
// 獲取所有勾選的值
const checkedVals = $('input[name="items"]:checked').map((_,el)=>el.value).get();
// 獲取值
const val = $('#txt').val();
// 設置值
$('#txt').val('新內容');
// 清空
$('#txt').val('');
// 獲取/設置屬性
$('#txt').attr('placeholder', '請輸入...');
$('#txt').prop('disabled', true); // disabled/readonly 用 prop
$('#txt').prop('readonly', true);
// 標準字符串 (application/x-www-form-urlencoded)
const str = $('#form').serialize();
// 數組對象 [{name, value}, ...]
const arr = $('#form').serializeArray();
// 對象 {name: value, ...} (需手動轉換或用插件)
const obj = {};
$('#form').serializeArray().forEach(f => {
if (obj[f.name]) {
// 同名轉數組 (如 checkbox)
obj[f.name] = [].concat(obj[f.name], f.value);
} else {
obj[f.name] = f.value;
}
});
function populateForm($form, data) {
$.each(data, (name, value) => {
const $ctrl = $form.find(`[name="${name}"]`);
if (!$ctrl.length) return;
if ($ctrl.is('select')) {
$ctrl.val(Array.isArray(value) ? value : [value]); // 兼容多選
} else if ($ctrl.is(':radio')) {
$ctrl.filter(`[value="${value}"]`).prop('checked', true);
} else if ($ctrl.is(':checkbox')) {
const vals = Array.isArray(value) ? value : [value];
$ctrl.each(function() { this.checked = vals.includes(this.value); });
} else {
$ctrl.val(value); // text/password/textarea/hidden
}
});
}
@ 屬性選擇器前綴.prop() 處理 checked/selected/disabled 等布爾屬性.val() 統一獲取/設置值,替代 .attr('value')map().join('') 替代循環 append,性能更優.on('change', fn) 替代內聯 onchange| 操作 | Select | Radio | Checkbox | Text/Textarea |
|---|---|---|---|---|
| 獲取值 | .val() | (':checked').val() | (':checked').map(...).get() | .val() |
| 獲取文本 | .find('option:selected').text() | — | — | — |
| 設置值 | .val(v) | ('[value=v]').prop('checked',true) | .prop('checked',true/false) | .val(v) |
| 禁用 | .prop('disabled',true) | .prop('disabled',true) | .prop('disabled',true) | .prop('disabled',true) |
| 清空/重置 | .empty().append(...)或.val('') | .prop('checked',false) | .prop('checked',false) | .val('') |
掌握這套統一 API,表單交互開發效率提升 80%。記住核心口訣:**值用 val(),狀態用 prop(),選擇器拋棄 @,動態構建用 map/join**。