/**
* 獲取控件值
* @param {string} controlID 控件 id 或 name
* @param {string} controlType 類型:text/radio/select/checkbox
* @returns {string} 值(checkbox 多值逗號分隔)
*/
function JqGetValue(controlID, controlType) {
var objValue = "";
switch (controlType) {
case 'text': // 文本框/隱藏域/密碼框/textarea
objValue = $.trim($("#" + controlID).val());
break;
case 'radio': // 單選組(同 name)
objValue = $("input[name='" + controlID + "']:checked").val() || "";
break;
case 'select': // 下拉框
objValue = $("#" + controlID).val() || "";
break;
case 'checkbox': // 多選組(同 name)
$("input[name='" + controlID + "']:checked").each(function() {
objValue += $(this).val() + ",";
});
if (objValue) objValue = objValue.slice(0, -1); // 去尾逗號
break;
default:
break;
}
return objValue;
}
/**
* 設置控件值
* @param {string} controlID 控件 id 或 name
* @param {string} controlType 類型
* @param {string} controlValue 值(checkbox 多值逗號分隔)
*/
function JqSetValue(controlID, controlType, controlValue) {
switch (controlType) {
case 'text':
$("#" + controlID).val(controlValue);
break;
case 'radio':
$("input[name='" + controlID + "'][value='" + controlValue + "']").prop("checked", true);
break;
case 'select':
$("#" + controlID).val(controlValue);
break;
case 'checkbox':
var values = controlValue.split(",");
$.each(values, function(i, v) {
$("input[name='" + controlID + "'][value='" + v + "']").prop("checked", true);
});
break;
default:
break;
}
}
| 場景 | 獲取值 | 設置值 | 注意 |
|---|---|---|---|
| 文本框 | .val() | .val(v) | .attr('value') 僅獲取初始屬性值,非當前值 |
| 單選組 | :checked 選中器 | [value='v'] + .prop('checked',true) | 同 name 分組,.attr('checked') 不穩定 |
| 下拉框 | .val() | .val(v) | 多選 select[multiple] 返回數組 |
| 多選組 | each 遍歷拼接 | split 遍歷 .prop('checked',true) | 同 name 分組,值用逗號分隔 |
.val() / .prop():jQuery 1.6+ .prop() 處理布爾屬性(checked/selected/disabled),.attr() 處理 HTML 屬性.text() 或轉義,避免 .html() 注入
// 表單序列化為對象(含所有類型)
function serializeForm(formId) {
var data = {};
$("#" + formId + " :input").each(function() {
var $this = $(this), name = $this.attr("name"), type = $this.attr("type");
if (!name) return;
if (type === "radio" || type === "checkbox") {
if ($this.is(":checked")) {
data[name] = data[name] ? data[name] + "," + $this.val() : $this.val();
}
} else {
data[name] = $this.val();
}
});
return data;
}
// 表單重置(原生 reset 不清空 hidden,需手動)
function resetForm(formId) {
$("#" + formId)[0].reset(); // 原生重置
$("#" + formId + " input[type=hidden]").val(""); // 額外清空 hidden
}
掌握 .val()、.prop('checked')、選中器 :checked、屬性選中器 [value='x'] 核心 API,封裝統一獲取/設置函數,配合表單序列化/重置工具,大幅減少表單處理樣板代碼,提升開發效率與代碼質量。