验证表单的时候经常需要获取表单中name='***'的元素的值,然后加以判断。jQuery中提供了jQuery.serizlizeArray来将表单序列化成一个数组。尽管如此,数组还是不方便我们操作,我需要讲表单序列化成一个对象。这样更方便于我们操作。
下面是代码:
/** * @author gaohuia */ (function($){ $.fn.extend({ serializeObject:function(){ if(this.length>1){ return false; } var arr=this.serializeArray(); var obj=new Object; $.each(arr,function(k,v){ obj[v.name]=v.value; }); return obj; } }); })(jQuery); /** * @author gaohuia */ (function($){ $.fn.extend({ serializeObject:function(){ if(this.length>1){ return false; } var arr=this.serializeArray(); var obj=new Object; $.each(arr,function(k,v){ obj[v.name]=v.value; }); return obj; } }); })(jQuery);
测试
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <FCK:meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type="text/javascript" src="js/jquery.js"></script> <script type="text/javascript" src="js/jQuery.formtool.js"></script> <title>无标题文档</title> <script language="javascript"> $(function(){ $(":button").click(function(){ var test=$("form").serializeObject(); alert(test.id); }); }); </script> </head> <body> <form action="" method="get"><input name="id" type="hidden" value="110" /> <input name="test" type="text" /> <input name="" type="button" /> </form> </body> </html> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <FCK:meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type="text/javascript" src="js/jquery.js"></script> <script type="text/javascript" src="js/jQuery.formtool.js"></script> <title>无标题文档</title> <script language="javascript"> $(function(){ $(":button").click(function(){ var test=$("form").serializeObject(); alert(test.id); }); }); </script> </head> <body> <form action="" method="get"><input name="id" type="hidden" value="110" /> <input name="test" type="text" /> <input name="" type="button" /> </form> </body>
以上就是jQuery将表单序列化成一个Object对象的实例的内容,更多相关内容请关注PHP中文网(www.php.cn)!