前端开发注意细节总结

1、搜索时,文本框的内容一般去掉前后空格

  (1)引用jquery时直接用$.trim() 方法即可

  (2)无jquery库时要用正则判断

     function trim(str){ //删除左右两端的空格
         return str.replace(/(^s*)|(s*$)/g, "");
     }
     function ltrim(str){ //删除左边的空格
         return str.replace(/(^s*)/g,"");
     }
     function rtrim(str){ //删除右边的空格
         return str.replace(/(s*$)/g,"");
     }

  详细链接:http://blog.sina.com.cn/s/blog_4934a04a0100kmqr.html

2、文件上传时文件类型

  (1)input type=“file”  加accept属性,上传只看到相应文件类型;W3C上建议在服务器上限制

  (2)  var t1 = "";
          if(_this.value.indexOf("\")>=0){ //_this为文件上传input节点,意思包含\
                t1 = _this.value.lastIndexOf("\");//t1等于最后一个\出现的位置
          } else {
                t1 = _this.value.lastIndexOf("/");//t1等于最后一个/出现的位置
          }
    
        var varrealfile = _this.value.substring(t1+1);//varrealfile 为最后一个\或/之后的字符串
        var varrealfiletype = (varrealfile.substring(varrealfile.lastIndexOf(".") + 1,varrealfile.length)).toLowerCase();  //取出文件后缀如果有大写将全部转换为小写


        if(!(varrealfiletype == "jpg"|| varrealfiletype=='jpeg' || varrealfiletype =='png'|| varrealfiletype =='gif')){ 
              return false;
        }

 3.有时$("#postRadio").attr("checked",true);和$("#postRadio").attr("checked",“checked”);在页面上不管用,是因为jquery的兼容性有问题,用 $("#houseRadio").prop("checked")可以解决 

那么,什么时候使用attr(),什么时候使用prop()?
1.添加属性名称该属性就会生效应该使用prop();
2.是有true,false两个属性使用prop();
3.其他则使用attr();
项目中jquery升级的时候大家要注意这点!


以下是官方建议attr(),prop()的使用:


Attribute/Property.attr().prop()
accesskey  
align  
async
autofocus
checked
class  
contenteditable  
draggable  
href  
id  
label  
location ( i.e. window.location )
multiple
readOnly
rel  
selected
src  
tabindex  
title  
type  
width ( if needed over .width() )  

jquery1.6版本以上对attr进行升级,多了个prop、prop是对页面效果的渲染。
attr只是对值执行更改,所以通常同来取值或设置。像单选框复选框之类的,设置之后页面效果需要重新渲染的建议用prop



4.toggle切换点击事件在jquery1.9版本不支持
5.checkbox 选中判断
$("input[type='checkbox']").is(':checked')
选中为true ,未选中为false

原文地址:https://www.cnblogs.com/nana-share/p/5276086.html