Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Zepto源码分析-form模块 #15

Open
mominger opened this issue Apr 14, 2015 · 0 comments
Open

Zepto源码分析-form模块 #15

mominger opened this issue Apr 14, 2015 · 0 comments

Comments

@mominger
Copy link
Owner

源码注释

    //     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,buttonfile和未被选中的radiocheckbox
        //原因是这些元素不需要传递给服务器
      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)

API

form 2 2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant