首页 > 技术文章 > 常用的表单操作

liwuming 2016-12-21 10:37 原文

 

 

 

常用的表单操作

 

1、在制作图片上传时,前端页面经常会需要判断图片的类型,图片的大小什么的,如果不做这些判断交给服务器处理,无疑会增加服务器的压力。   

 

 1           <tr>
 2                     <th>本地图片:</th>
 3                     <td>
 4                         <input value="" name="specImg" type="file" id="specImg_file" class="none"/>
 5                         <button class="btn" id="selectSpecImg" type="button"><span class="add">选择规格图图</span></button>
 6                     </td>
 7                 </tr>
 8                 <tr>
 9                     <th>本地图片:</th>
10                     <td>
11                         <input value="确定" type="submit" />
12                     </td>
13                 </tr>

 

js处理

 1     $("#selectSpecImg").on("click",function(){
 2                 $("#specImg_file").click().off("change").on("change",function(){
 3                     var file_info = $(this)[0].files[0];
 4                     var type = ["image/gif","image/jpeg","image/png"];    //允许的mime文件类型
 5                     
 6                     if($.inArray(file_info.type,type) < 0){        //【文件类型判断】如果不包含,则会返回-1
 7                         、、、、、//此处省略代码若干
15 } 16 17 if(file_info.size / 1024 > 100){         //【文件大小判断】 18 、、、、//此处省略代码若干
              } 27 }); 28 });

 

 

2、阻止表单的默认行为:

 1       //当提交表单时,会触发sumit()事件
 2             $("#uploadImg").submit(function(e){
 3                 //使用preventDefault()函数来阻止对表单的提交
 4                 e.preventDefault();
 5                 var file_info = $("#specImg_file")[0].files[0];
 6                 var type = ["image/gif","image/jpeg","image/png"];// 
 7                 
 8                 if($.inArray(file_info.type,type) < 0){        //如果不包含,则会返回-1
 9                     art.dialog({
10                         title:"温馨提示",
11                         icon: "error",
12                         opacity: 0.5,    // 透明度
13                         content: "不符合的文件类型,请选择图片...",
14                         lock:true,
15                         okVal:"确定",
16                     });
17                     return false;
18                 }else if(file_info.size / 1024 > 100){
19                     art.dialog({
20                         title:"温馨提示",
21                         icon: "error",
22                         opacity: 0.5,    // 透明度
23                         content: "图片文件过大,请重新选择图片...",
24                         lock:true,
25                         ok:"确定",
26                     });
27                 
28                     return false;
29                 }else{
30                     return true;
31                 }
32             });

 

推荐阅读