jquery.form.js清空表单数据方法解析
作者:清欢时间:2026-10-27 23:24:16浏览:331
本文深入解析jquery.form.js库中的clearForm方法,该方法用于清空表单数据。通过独立提取该段代码,展示了如何重置input、select、checkbox等元素的状态,并特别处理了file类型在IE浏览器下的兼容性问题及hidden字段的可选清理逻辑,为开发者提供实用的参考实现。
jquery.form.js清空表单方法解析
这段代码源自jquery.form.js库,因其极高的实用价值,常被单独提取使用。该实现简洁明了,是学习相关功能的优秀参考范例。
具体实现代码如下:
/**
* 清空表单数据。对表单内的输入字段执行以下操作:
* - 文本输入框的'value'属性被设置为空字符串
* - 选择元素(select)的'selectedIndex'属性被设置为-1
* - 复选框(checkbox)和单选按钮(radio)的'checked'属性被设置为false
* - 类型为submit、button、reset和hidden的输入框不受影响
* - button元素也不受影响
*/
$.fn.clearForm = function(includeHidden) {
return this.each(function() {
$('input,select,textarea', this).clearFields(includeHidden); //this表示设置上下文环境,有多个表单时只作用调用的表单
});
};
$.fn.clearFields = $.fn.clearInputs = function(includeHidden) {
var re = /^(?:color|date|datetime|email|month|number|password|range|search|tel|text|time|url|week)$/i; // 'hidden' is not in this list
return this.each(function() {
var t = this.type, tag = this.tagName.toLowerCase();
if (re.test(t) || tag == 'textarea') {
this.value = '';
}
else if (t == 'checkbox' || t == 'radio') {
this.checked = false;
}
else if (tag == 'select') {
this.selectedIndex = -1;
}
else if (t == "file") {
if (/MSIE/.test(navigator.userAgent)) {
$(this).replaceWith($(this).clone(true));
} else {
$(this).val('');
}
}
else if (includeHidden) {
// includeHidden can be the value true, or it can be a selector string
// indicating a special test; for example:
// $('#myForm').clearForm('.special:hidden')
// the above would clean hidden inputs that have the class of 'special'
if ( (includeHidden === true && /hidden/.test(t)) ||
(typeof includeHidden == 'string' && $(this).is(includeHidden)) ) {
this.value = '';
}
}
});
};作者最新文章
JS转整数出现NaN怎么办?常见异常处理方案
2026-11-05 16:27:31
推荐几款免安装的在线JS压缩工具
2026-11-05 14:54:53
JS怎么使用JSON.stringify实现JSON格式化与缩进
2026-11-04 10:47:30
CodePen、JSFiddle 与 StackBlitz:主流 JS 在线编辑器对比
2026-11-03 21:07:49
JS字符串转数字后怎么正确判断是否为有效数值
2026-11-03 20:04:15
