8个原生JSJQuery实用技巧

选择所有子元素(排除最后一个)

element:not(:last-child){}自定义原生input="file"的样式

//自定义上传样式liid="upload-btn"class="default-image"imgsrc="="alt=""div请上传图片/div!--上传(隐藏原生的input)--inputtype="file"id="upload"class="hide"/li//模拟原生input点击事件$(#upload-btn).click(function(){$(#upload).click();})attr()和prop()的区别attr表示HTML文档节点的属性,prop表示JS对象的属性

!--这里的id、class、data-id均为div的attr--divid="demo"class="demo"data-id="1"/div

//这里的name、age均为obj对象的propletobj={name:wen,age:18}

attr()底层依赖的是getAttribute()和setAttribute()两个方法,prop()依赖原生JS中的对象属性获取和设置方式。

attr()是jQuery1.0版本就有的函数,prop()是jQuery1.6版本新增的函数

对于表单元素的checked、selected、disabled等属性,在jQuery1.6之前,attr()获取这些属性的返回值为Boolean类型:如果被选中(或禁用)就返回true,否则返回false。

但从1.6开始,使用attr()获取这些属性的返回值为String类型,如果被选中(或禁用)就返回checked、selected或disabled,否则(即元素节点没有该属性)返回undefined。

在某些版本中,这些属性值表示文档加载时的初始状态值,即使之后更改了这些元素的选中(或禁用)状态,对应的属性值也不会发生改变。因为jQuery认为:attribute的checked、selected、disabled就是表示该属性初始状态的值,property的checked、selected、disabled才表示该属性实时状态的值(值为true或false)。

因此,在jQuery1.6及以后版本中,请使用prop()函数来设置或获取checked、selected、disabled等属性。对于其它能够用prop()实现的操作,也尽量使用prop()函数。

原生ajax导出二进制文件(文件流)

varurl=`/export?start_time=${start_time}`;varxhr=newXMLHttpRequest();//也可以使用POST方式,根据接口xhr.open("GET",url,true);//返回类型blob,XMLHttpRequest支持二进制流类型xhr.responseType="blob";xhr.onload=function(){if(this.status===){//使用response作为返回,而非responseTextvarblob=this.response;varreader=newFileReader();//转换为base64,可以直接放入a标签hrefreader.readAsDataURL(blob);reader.onload=function(e){//转换完成,创建一个a标签用于下载vara=document.createElement("a");//获取当前导出时间varnowDate=format(newDate());a.download=`文件名_${nowDate}.xlsx`;a.href=e.target.result;a.click();};}};xhr.send();jquery实现远程搜索(模仿iview)

//-----------远程搜索start------------//远程搜索接口路径varsearchUrls=["/productManager/index"];//请求下拉列表functionremoteSearch(val,idx){varthat=$("#"+val+"");$("#"+val+"-dropdown").show();$("#select-"+val+"-id").val("");varname=$(that).val().trim();vardata={name};$("#"+val+"-dropdown").html(divclass="search-loading"加载中.../div);$.ajax({type:"GET",url:searchUrls[idx],data,success:function(res){varlist=res.data

[];varstr="";if(list.length){$.each(list,function(index,item){str+=`liclass="select-item"data-id=${item.id}data-name=${item.name}${item.name}/li`;});$("#"+val+"-dropdown").html(str);}else{$("#"+val+"-dropdown").html(divclass="empty-search"无匹配数据/div);}},error:function(error){console.log(error);},});}//防抖函数functiondebounce(fn,delay=){vartimer=null;returnfunction(){varcontext=this;varargs=arguments;timerclearTimeout(timer);timer=setTimeout(()={fn.apply(context,args);},delay);};}vardebounceCategory=debounce(remoteSearch.bind(null,"category",0),);//绑定input事件$("#category").on("input",debounceCategory);//失焦隐藏下拉列表functionhideDropdown(str){setTimeout(()={varid=$("#select-"+str+"-id").val();if(!id)$("#"+str+"").val("");$("#"+str+"-dropdown").hide();},);}//失焦$("#category").blur(hideDropdown.bind(null,"category"));//选择下拉列表某一项functionselectItem(that,str){varid=$(that).attr("data-id");varname=$(that).attr("data-name");$("#"+str+"").val(name);$("#select-"+str+"-id").val(id);$("#"+str+"-dropdown").hide();}//选择$("#category-dropdown").on("click",".select-item",function(){selectItem($(this),"category");});JQuery切换弹窗状态

functiontoggleModal(str,bool){varmodal=modalInfo[str];bool?$(modal).stop().fadeIn():$(modal).stop().fadeOut();}JQuery导入文件

//点击导入functionselectFile(){$("#import-product-file").click();}//导入文件$("#import-product-file").change(function(){varfileItem=$(this)[0].files[0];varfileName=fileItem.name;$("#import-file-name").html(fileName);});//确认导入functionsubmitImport(){varfileItem=$("#import-product-file")[0].files[0];if(!fileItem)returnalert("请先选择文件!");varformData=newFormData();formData.append("file",fileItem);$("#import-product-file").val("");$.ajax({type:"POST",url:"/import",data:formData,contentType:false,processData:false,dataType:"json",success:function(res){if(res.code===0res.status){alert("导入成功!");getList();}else{alert(res.msg

"导入失败!");}},error:function(error){console.log(error);},});}JQuery实现监听input字数

//监听键盘输入事件(实时字数)$("#category-desc").on("input",function(){varcurrentCount=$(this).val().length;$("#category-current-count").html(currentCount);});叫我欧文就好

明天想吃麦当劳



转载请注明:http://www.sonphie.com/lcbx/14519.html

网站简介| 发布优势| 服务条款| 隐私保护| 广告合作| 网站地图| 版权申明

当前时间: