相信不少人都用過jq的表單序列化serialize()方法,由於這能很方便地幫你把表單裏全部的非禁用輸入控件序列化爲 key/value 對象,不須要你再去一個個地拼接參數了。javascript
這是一個很好用的函數,用過的你確定知道。可是ghostsf最近發現一個小bug(也許不該該叫bug,姑且稱之)。就是當radio或checkbox 未選中時,沒有序列化到對象中。html
什麼緣由呢?下面分析之:
瞄一眼源碼:From jQuery JavaScript Library v2.1.4java
jQuery.fn.extend({ serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function() { // Can add propHook for "elements" to filter or add form elements var elements = jQuery.prop( this, "elements" ); return elements ? jQuery.makeArray( elements ) : this; }) .filter(function() { var type = this.type; // Use .is( ":disabled" ) so that fieldset[disabled] works return this.name && !jQuery( this ).is( ":disabled" ) && rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && ( this.checked || !rcheckableType.test( type ) ); }) .map(function( i, elem ) { var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val ) { return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } });
不得不說代碼寫得很凝練。咱們能夠看到咱們調用的serialize(),實際上是走的param()方法,這個方法查閱jq手冊便可得知,其做用是將數組或對象序列化爲一個 key/value 對象。node
顯然這個方法不是咱們要看的,重點就是serializeArray()了。
簡單看下代碼(只是簡單看了下並未嚴格測試校驗,可能有缺漏)。能夠看到map裏對於val的處理,判斷到是數組的時候jQuery.isArray( val ) ?
直接使用map進行了遍歷,這個時候若是這個數組的length是0呢?那麼天然當radio或checkbox 未選中時,這邊的數組長度是爲0的,因此這裏就把radio或checkbox給漏掉了。jquery
那麼怎麼解決呢?直接改源碼?這也太粗暴了吧。數組
ghostsf心血來潮寫了一個jq拓展,代碼以下:(並不要臉地命名爲ghostsf_serialize):函數
//爲jquery.serializeArray()解決radio,checkbox未選中時沒有序列化的問題 $.fn.ghostsf_serialize = function () { var a = this.serializeArray(); var $radio = $('input[type=radio],input[type=checkbox]', this); var temp = {}; $.each($radio, function () { if (!temp.hasOwnProperty(this.name)) { if ($("input[name='" + this.name + "']:checked").length == 0) { temp[this.name] = ""; a.push({name: this.name, value: ""}); } } }); //console.log(a); return jQuery.param(a); };
怎麼使用呢?
引入便可,而後就是你經常使用的測試
$(form).ghostsf_serialize()
了。this
這樣就很輕鬆地解決此問題了。本身動手豐衣足食。spa
轉自:http://www.ghostsf.com/tools/389.html