Zepto源码分析-form模块
2015-04-09 20:14
567 查看
源码注释
方法图
// Zepto.js // (c) 2010-2015 Thomas Fuchs // Zepto.js may be freely distributed under the MIT license. ;(function($){ /** * 序列表单内容为JSON数组 * 返回类似[{a1:1},{a2:2}]的数组 * @returns {Array} */ $.fn.serializeArray = function() { var name, type, result = [], //{name:value}形式加入到结果数组中 add = function(value) { //value是数组,递归添加到数组中 //注意这里的写法 value.forEach(add) 将value数组递归的每一项传入add // 如 {a:[1,2,3]} --> [{a:1},{a:2},{a:3}] if (value.forEach) return value.forEach(add) result.push({ name: name, value: value }) } // if (this[0]) $.each(this[0].elements, function(_, field){ type = field.type, name = field.name //排除fieldset,禁用元素,submit,reset,button,file和未被选中的radio,checkbox //原因是这些元素不需要传递给服务器 if (name && field.nodeName.toLowerCase() != 'fieldset' && !field.disabled && type != 'submit' && type != 'reset' && type != 'button' && type != 'file' && ((type != 'radio' && type != 'checkbox') || field.checked)) //{name:value}形式加入到结果数组中 add($(field).val()) }) return result } /** * 序列表表单内容为查询字符串 * 转换成 a=1&b=2 * @returns {string} */ $.fn.serialize = function(){ var result = [] this.serializeArray().forEach(function(elm){ // 每个key-value,都保守URI编码 result.push(encodeURIComponent(elm.name) + '=' + encodeURIComponent(elm.value)) }) return result.join('&') } /** * 提交表单 * @param callback * @returns {*} */ $.fn.submit = function(callback) { //0 in arguments 判断是否传了回调函数 // 这里不应用bind,所有事件应该统一用on //传了回调,就当成绑定submit事件 if (0 in arguments) this.bind('submit', callback) //没有传回调,当成直接提交 else if (this.length) {//有表单元素 var event = $.Event('submit') //第一个表单直接触发submit事件 //如果绑定过submit事件,此处会执行submit绑定函数 //注意,这里只是抛出事件,并不会提交表单 this.eq(0).trigger(event) //如果未阻止浏览器默认事件,调用document.forms[0].submit()执行默认处理 //document.forms[0].submit()提交表单 if (!event.isDefaultPrevented()) this.get(0).submit() } return this } })(Zepto)
方法图
相关文章推荐
- 一个普通的 Zepto 源码分析(一) - ie 与 form 模块
- Zepto事件模块源码分析
- 读Zepto源码之Form模块
- zepto 事件模块源码分析
- 一个普通的 Zepto 源码分析(二) - ajax 模块
- Zepto源码分析-ajax模块
- 一个普通的 Zepto 源码分析(三) - event 模块
- Zepto源码分析-callbacks模块
- 读Zepto源码之Form模块
- Zepto源码分析-动画(fx fx_method)模块
- Zepto源码之form模块
- MooTools 1.4 源码分析 - (关于Core、Type等模块分析)
- Glusterfs之rpc模块源码分析(上)之RPC概述
- Glusterfs之nfs模块源码分析(中)之Glusterfs实现NFS服务器
- Glusterfs之rpc模块源码分析(中)之Glusterfs的rpc模块实现(3)
- Glusterfs之rpc模块源码分析(中)之Glusterfs的rpc模块实现(1)
- Glusterfs之rpc模块源码分析(中)之Glusterfs的rpc模块实现(1)
- Glusterfs之nfs模块源码分析(中)之Glusterfs实现NFS服务器
- Glusterfs之nfs模块源码分析(上)之nfs原理和协议
- Nginx技术交流Q群:225942451(探讨安装、部署、模块开发、源码分析,及其他知名服务端开源软件)