本文在 @ 選擇器),補充動態構建、數據綁定、驗證集成、TypeScript 類型、無障礙支持,構建生產級表單操作參考手冊。
// ❌ 棄用
$("input[@name='sex'][@checked]")
$("select[@name='country'] option[@selected]")
// ✅ 標準
$("input[name='sex']:checked")
$("select[name='country'] option:selected")
$("input[type='radio']:checked")
$("input[type='checkbox']:checked")
/**
* 將表單序列化為 { name: value } 對象
* - 同名 checkbox/radio/select-multiple → 陣列
* - 其他 → 字符串
*/
export function serializeForm($form) {
const data = {};
$form.serializeArray().forEach(({name, value}) => {
if (data[name] !== undefined) {
data[name] = Array.isArray(data[name]) ? [...data[name], value] : [data[name], value];
} else {
data[name] = value;
}
});
return data;
}
// 使用
const formData = serializeForm($('#myForm'));
// { username: "admin", roles: ["admin","editor"], theme: "dark" }
/**
* 將數據對象回填到表單
* 支持: text/password/textarea/hidden/select/radio/checkbox/file(僅清空)
*/
export function populateForm($form, data) {
Object.entries(data).forEach(([name, value]) => {
const $ctrls = $form.find(`[name="${CSS.escape(name)}"]`);
if (!$ctrls.length) return;
const type = $ctrls.attr('type');
const tag = $ctrls.prop('tagName').toLowerCase();
if (tag === 'select') {
const vals = Array.isArray(value) ? value : [value];
$ctrls.val(vals.map(String)); // 統一轉字符串匹配
} else if (type === 'radio') {
$ctrls.filter(`[value="${CSS.escape(String(value))}"]`).prop('checked', true);
} else if (type === 'checkbox') {
const vals = Array.isArray(value) ? value.map(String) : [String(value)];
$ctrls.each(function() { this.checked = vals.includes(this.value); });
} else if (tag === 'textarea' || ['text','password','email','number','hidden'].includes(type)) {
$ctrls.val(value);
} else if (type === 'file') {
// file input 安全限制不可設置值,僅可清空
$ctrls.val('');
}
});
}
interface FormDataMap {
[key: string]: string | string[] | number | boolean | File | FileList;
}
interface FormOperator {
serialize(): FormDataMap;
populate(data: FormDataMap): void;
validate(): ValidationResult;
reset(): void;
}
function createFormOperator($form: JQuery): FormOperator {
return {
serialize: () => serializeForm($form),
populate: (data) => populateForm($form, data),
validate: () => { /* 集成 validator.js 或 HTML5 驗證 */ },
reset: () => $form[0].reset()
};
}
async function loadSelectOptions($sel, apiUrl, params = {}) {
$sel.prop('disabled', true).empty().append('');
try {
const items = await $.getJSON(apiUrl, params);
const html = items.map(item =>
``
).join('');
$sel.empty().append(html).prop('disabled', false);
// 觸發 change 以便監聽器響應
$sel.trigger('change');
} catch (e) {
$sel.empty().append('').prop('disabled', false);
}
}
function makeSearchable($sel, options = {}) {
const $wrapper = $('');
const $input = $('');
const $options = $sel.find('option').clone();
$sel.hide().after($wrapper.append($input)).after($options); // 簡化版邏輯
// 生產環境強烈建議引入 Select2 / Choices.js / Tom Select
}
function getGroupValue($form, name) {
const $radios = $form.find(`input[type="radio"][name="${CSS.escape(name)}"]`);
const $checkboxes = $form.find(`input[type="checkbox"][name="${CSS.escape(name)}"]`);
if ($radios.length) return $radios.filter(':checked').val() || null;
if ($checkboxes.length) return $checkboxes.filter(':checked').map((_,el)=>el.value).get();
return null;
}
function setGroupValue($form, name, value) {
const $radios = $form.find(`input[type="radio"][name="${CSS.escape(name)}"]`);
const $checkboxes = $form.find(`input[type="checkbox"][name="${CSS.escape(name)}"]`);
if ($radios.length) {
$radios.filter(`[value="${CSS.escape(String(value))}"]`).prop('checked', true);
} else if ($checkboxes.length) {
const vals = Array.isArray(value) ? value.map(String) : [String(value)];
$checkboxes.each(function() { this.checked = vals.includes(this.value); });
}
}
function validateForm($form) {
const nativeValid = $form[0].checkValidity();
$form[0].reportValidity(); // 顯示瀏覽器原生提示
return nativeValid;
}
// 自定義規則
$.validator?.addMethod('chineseName', (value) => /^[\u4e00-\u9fa5]{2,10}$/.test(value), '請輸入中文姓名');
<label for="id"> 關聯所有輸入框aria-describedby 關聯 role="alert" 元素required + aria-required="true"| 原文代碼 | 問題 | 修正 |
|---|---|---|
select[@name=...] | @ 選擇器已移除 | select[name=...] |
option[@selected] | 同左 | option:selected |
.attr('checked', true) | 屬性 vs 屬性混淆 | .prop('checked', true) |
.attr('value', '') | 設置值應用 val() | .val('') |
$('#select_id')[0].selectedIndex = 1 | 混用原生屬性 | $sel.prop('selectedIndex', 1) |
appendTo("#select") 字符串拼接 | XSS 風險、性能差 | .append(htmlString) 或構建 DOM |
.val(),狀態 .prop(),屬性 .attr(),選擇器無 @serializeForm / populateForm / getGroupValue / setGroupValue 覆蓋 95% 場景.empty().append(htmlString) 批量構建,避免循環 appendcheckValidity() + 自定義規則將這套工具函數封裝為 @/utils/formOps,表單頁開發從「拼湊選擇器」變為「調用語義化 API」,代碼可讀性、可維護性、可測試性全面提升。