jquery.form.js清空表单数据方法解析

作者:清欢

时间:2026-10-27

浏览:330

本文深入解析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 = '';
 }
 }
 });
};

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章