总结:常用js方法

1函数注释 2/** 3 * 获取页面缓存 4 * @method getSession 函数名 5 * @param 参数名 字符串类型,需要获取的key名 6 * @return 变量名 对象类型 7 */ 8 9 10img.onload定义和用法 11onload 事件在图片加载完成后立即执行。 12 13 14判断设备 15const userAgent = navigator.userAgent.toLowerCase() 16const isMobile = /mobile/i.test(userAgent) 17const isAndroid = /android/i.test(userAgent) 18const isIOS = /iphone|ipad|ipod/i.test(userAgent) 19const isWX = /MicroMessenger/i.test(userAgent) 20 21判断是否手机号码 22const isPhoneNum = num => { 23 return /^1\d{10}$/.test(num) 24} 25 26对Session缓存的获取,保存,删除 27const getSession = key => { 28 let value = sessionStorage.getItem(key) 29 if (value !== '' && value !== null) { 30 return JSON.parse(value) 31 } 32 return {} 33} 34const saveSession = (key, value) => sessionStorage.setItem(key, JSON.stringify(value)) 35const removeSession = key => sessionStorage.removeItem(key) 36 37对localStorage缓存的获取,保存,删除 38 getLocal: key => { 39 let value = localStorage.getItem(key) 40 if (value !== '' && value !== null) { 41 return JSON.parse(value) 42 } 43 return {} 44 }, 45 saveLocal: (key, value) => localStorage.setItem(key, JSON.stringify(value)), 46 removeLocal: key => localStorage.removeItem(key) 47 48 49js精确计算 50formatNum = function(f, digit) { 51 var m = Math.pow(10, digit); 52 return parseInt(f * m, 10) / m; 53} 54 55生成随机32位字符 56const uuid = () => { 57 const S4 = () => (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1) 58 return S4() + S4() + '-' + S4() + '-' + S4() + '-' + S4() + '-' + S4() + S4() + S4() 59} 60 61解析url地址 62~(function (str) { 63 str.queryURLParameter = function () { 64 var obj = {}, 65 reg = /([^?=&#]+)(?:=([^?&#]+)?)/g 66 this.replace(reg, function () { 67 var key = arguments[1], 68 value = arguments[2] || null 69 obj[key] = value 70 }) 71 return obj 72 } 73}(String.prototype)) 74 75 let str = window.location.search 76 return str.queryURLParameter() 77 78提高眼界:解析url地址 79~function (pro) { 80 pro.queryURLParameter = function () { 81 var obj = {}, 82 reg = /([^?=&#]+)(?:=([^?=&#]+)?)/g; 83 this.replace(reg, function () { 84 var key = arguments[1], 85 value = arguments[2] || null; 86 obj[key] = value; 87 }); 88 return obj; 89 } 90}(String.prototype); 91 92var str = 'http://www.zhufengpeixun.cn/stu/?lx=1&name=&sex=#teacher'; 93console.log(str.queryURLParameter()); 94 95 96动态生成标签,如script,iframe标签等 97function inject (container, src, tag = 'iframe') { 98 let context = document.createElement(tag) 99 context.id = 'i-' + new Date().getTime() 100 if (tag === 'link') { 101 context.href = src 102 context.rel = 'stylesheet' 103 } else { 104 context.src = src 105 } 106 document.querySelectorAll(container)[0].appendChild(context) 107 return new Promise((resolve, reject) => { 108 if (context.readyState) { 109 context.onreadystatechange = () => { 110 if (this.readyState == 'loaded' || this.readyState == 'complete') { 111 this.onreadystatechange = null 112 resolve(context) 113 } 114 } 115 } else { 116 context.onload = () => resolve(context) 117 } 118 }) 119} 120 121提示语: 122function showMsg (txt = '', Autoclose = true) { 123 if (txt == '') { 124 return false // 为空则不弹出 125 } 126 let msg = document.createElement('div') 127 msg.innerHTML = ` 128 <div className="msg" style=" 129 position: fixed; 130 left:50%; 131 top:50%; 132 transform: translate(-50%,-30%); 133 font-size: 0.28rem; 134 padding: 0.2rem 0.3rem; 135 border-radius: 0.08rem; 136 background: rgba(0, 0, 0, 0.8); 137 line-height: 1.5; 138 max-width: 4rem; 139 color: #fff; 140 word-break:break-all; 141 max-height:4rem; 142 overflow-x:auto; 143 z-index:9999999"; 144 id="show_tip"> 145 ${txt} 146 </div> 147 ` 148 document.body.appendChild(msg) 149 if (Autoclose) { 150 setTimeout(() => { 151 document.body.removeChild(msg) 152 }, 3000) 153 } else { 154 document.getElementById('show_tip').parentNode.onclick = function () { 155 document.body.removeChild(msg) 156 } 157 } 158} 159 160等待的显示和隐藏 161function loadingCom () { 162 let loadingElent = document.createElement('div') 163 let att = loadingElent.setAttribute('class', 'loading') 164 let attId = loadingElent.setAttribute('id', 'loading') 165 loadingElent.innerHTML = 166 ` 167 <div class="params" style="width:100%;height:100%;position: fixed;background:rgab(0,0,0,.3);"> 168 <div class="loading-com" style=" 169 width:1.25rem; 170 height:1.25rem; 171 top:50%; 172 left: 50%; 173 margin-left:-.625rem; 174 margin-top:-.605rem; 175 position: absolute;"> 176 <img src="https://h5game.gowan8.com/static/img/loading.gif" width="100%"> 177 </div> 178 </div> 179 ` 180 document.body.appendChild(loadingElent) 181} 182 183function removeLoading () { 184 var loading = document.getElementById('loading') 185 document.body.removeChild(loading) 186} 187 188 189// 合并对象方法 190const assign = Object.assign || function (t) { 191 // 合并参数 192 let n = arguments.length, s 193 for (let i = 1; i < n; i++) { 194 s = arguments[i] 195 for (var p in s) { 196 if (Object.prototype.hasOwnProperty.call(s, p)) { 197 t[p] = s[p] 198 } 199 } 200 } 201 return t 202} 203 204// 判断是否是空对象 205function isEmptyObject (obj) { 206 var name 207 for (name in obj) { 208 return false 209 } 210 return true 211} 212 213 214//设置cookie 215function setCookie(name,value){ 216 if(!name||!value) return; 217 var Days = 30;//默认30天 218 var exp = new Date(); 219 exp.setTime(exp.getTime() + Days*24*60*60*1000); 220 document.cookie = name + "="+ encodeURIComponent(value) +";expires="+ exp.toUTCString(); 221} 222 223//获取cookie 224function getCookie(name){ 225 var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)")); 226 if(arr != null) return decodeURIComponent(arr[2]); 227 return null; 228} 229 230//删除cookie 231function delCookie(name){ 232 var exp = new Date(); 233 exp.setTime(exp.getTime() - 1); 234 var cval=getCookie(name); 235 if(!cval) document.cookie=name +"="+cval+";expires="+exp.toUTCString(); 236} 237 238 239 240jQuery中对cookie的操作 241jQuery.cookie = function (name, value, options) { 242 if (typeof value != 'undefined') { // name and value given, set cookie //2个参数设置cookie 243 options = options || {}; 244 if (value === null) { 245 value = ''; 246 options.expires = -1; 247 } 248 var expires = ''; 249 if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) { 250 var date; 251 if (typeof options.expires == 'number') { 252 date = new Date(); 253 date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000)); 254 } else { 255 date = options.expires; 256 } 257 expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE 258 } 259 260 var path = options.path ? '; path=' + (options.path) : ''; 261 var domain = options.domain ? '; domain=' + (options.domain) : ''; 262 var secure = options.secure ? '; secure' : ''; 263 document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join(''); 264 } else { // only name given, get cookie //一个参数,读取cookie 265 var cookieValue = null; 266 if (document.cookie && document.cookie != '') { 267 var cookies = document.cookie.split(';'); 268 for (var i = 0; i < cookies.length; i++) { 269 var cookie = cookies[i].trim(); 270 // Does this cookie string begin with the name we want? 271 if (cookie.substring(0, name.length + 1) == (name + '=')) { 272 cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); 273 break; 274 } 275 } 276 } 277 return cookieValue; 278 } 279} 280 281 282 283 284switch case 用法 285switch (op_type) { 286 case 0: 287 that._customerService(paycbData, callback) 288 break; 289 case 1: 290 that._requestMidasPayment(dataFormidashi, paycbData, callback) 291 break; 292 case 2: 293 that._requestMidasPayment(dataFormidashi, paycbData, callback) 294 break; 295 case 3: 296 break; 297 case 4: 298 break; 299 case 5: 300 that._payCallback(paycbData, callback) //直接回调 301 break; 302 } 303 304 305 306 307全局配置url方法根据不同域名设置不同的模式,请求不同的地址 308let ENV = 'local' 309if (/gowanme/.test(location.hostname)) ENV = 'test' 310if (/demo/.test(location.hostname)) ENV = 'dev' 311if (/gowan8\.com/.test(location.hostname)) ENV = 'prod' 312const __gowanpayDomain = { 313 local: 'pay.gowanme.com', 314 dev: 'pay.gowanme.com', 315 test: 'pay.gowanme.com', 316 prod: 'pay.gowan8.com', 317 get () { 318 return `//${__gowanpayDomain[ENV]}/` 319 } 320} 321 322 323 微信内部H5支付(得到后台给的参数,发起支付即可) 324 function wxpay (config) { 325 FN.log('wxpay:', config) 326 let { 327 appId, 328 timeStamp, 329 nonceStr, 330 signType, 331 paySign, 332 redirectUrl 333 } = config 334 WeixinJSBridge.invoke( 335 'getBrandWCPayRequest', 336 { 337 appId, // 公众号名称,由商户传入 338 timeStamp, // 时间戳,自1970年以来的秒数 339 nonceStr, // 随机串 340 package: config.package, 341 signType, // 微信签名方式: 342 paySign // 微信签名 343 }, 344 function (res) { 345 if (res.err_msg === 'get_brand_wcpay_request:ok') { 346 FN.log('执行微信支付成功', res) 347 } 348 } 349 ) 350 } 351 352 353第三方浏览器直接打开app。 354安卓: 355var state = null; 356try { 357 if (scheme != '') { 358 openIframe.src = '【scheme】://【host】/【openwith】'; 359 } 360} catch (e) { } 361if (state) { 362 window.close(); 363} else { 364 location.href='下载地址'; 365} 366 367苹果: 368if (scheme != '') { 369 window.location.href = '【scheme】://'; 370} 371 372 373判断是不是一个函数 374typeof (this.confirmModalOptions.btnSubmitFunction) === 'function' 375 376抛出异常 377 throw Error('err:show不存在') 378 379 380技巧 381当某些值需要进行传递是,可以将值挂载在window上,然后再另外一个地方,通过window进行获取 382 383 384正则匹配数组或者使用任意符号包裹起来的内容 385 const str2 = strs 386 const reg = /\[(.+?)\]/g 387 str2.match(reg) 388例如: 389正则匹配指定<>括号内的内容,并进行删除 390// 对model进行处理 391function handlerModel(str=''){ 392 const reg = /\<(.+?)\>/g 393 if (str.match(reg)){ 394 let delStr = s.match(reg)[0] 395 return s.replace(delStr, '') 396 } 397} 398 399 400 401js删除节点 402var theParent = document.getElementById("bq_ly"); 403theParent.parentNode.removeChild(theParent); 404 405 406 407 408 409 410 411/** 412 * 验证是否有空格 413 * 414 * @param {} 415 * source 416 */ 417function checkSpace(source) { 418 var regex = /\s/g; 419 return regex.test(source); 420} 421 422 423/** 424 * 随机数UUID 425 * @return 426 */ 427function makeUUID() { 428 var S4 = function () { 429 return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1); 430 }; 431 return (S4() + S4() + S4() + S4() + S4() + S4() + S4() + S4()); 432} 433 434 435 436 437 438获取对象的键名,返回值是一个数组 439Object.keys(obj) 440 441获取对象的值,返回值是一个数组 442Object.values(obj) 443 444从一个对象中获取选中的键和值,返回一个新对象 445Object.select(obj, ['name', 'phone']) 446第一个参数obj,是需要选取的目标对象,第二个参数是一个数组。是具体需要获取的值 447 448把一个对象中,所有属性的值都清空 449object.clear(obj) 450 451发布订阅 452先订阅,再发布 453window.__subscribe = {} 454window.__subscribe['make_order'] = function () { 455 _this._makeOrder(token, args) 456 } 457在需要发布的地方发布,订阅案例 458if (window.__subscribe['make_order']) { 459 window.__subscribe['make_order']() 460 delete window.__subscribe['make_order'] 461 } 462 463理解:就是给window的__subscribe对象绑定一个方法,在需要用到的地方,执行该方法, 464执行完成后,再删除该方法 465 466额外理解, 4671 就是当执行某个方法的时候,能执行里面所有的方法 4682 里面所有的方法是一个数组,遍历得到这个数组,并进行执行 4693 数组里面的方法来自一个对象,这个对象可以生成很多个数组方法,可以参考用工厂模式 470 471 472 473工厂模式: 474所谓的工厂模式,就是一个方法,通过传入不同的参数,返回不同的方法, 或者对象,这个模式称为工厂模式,出来的产品都是一样的,所以是工厂模式 475例子: 476function(a,b,){ 477if(a=='xxx'){ 478return obja 479} 480if(b=='xxx){ 481return objb 482} 483} 484 485 486 js调用App 方法 487假设方法名为 JAMS__mark 488android 系统: 489  window.android.JAMS__mark(params) // @params为传入的参数, app内可以收到 490ios 系统: 491 window.webkit.messageHandlers.JAMS__mark.postMessage(params) // @params为传入的参数, app内可以收到 492 493封装后为: 494export function JAMS__mark() { 495 if (/android/i.test(navigator.userAgent)) { 496 try { 497 window.android.JAMS__mark(params) 498 } catch (e) { 499 console.log(e) 500 } 501 } else if (/ios|iphone|ipod|pad/i.test(navigator.userAgent)) { 502 try { 503 window.webkit.messageHandlers.JAMS__mark.postMessage(params) 504 } catch (e) { 505 console.log(e) 506 } 507 } 508} 509 510 511App调用js方法 512App调用js 方法需要js将方法挂载在window下,这样App才能调用到方法, 513假设方法名叫 JAMS__success 514window.JAMS__success = function () { 515  // do some thing 516  // if need some params ,you can alse return it 517  return params; 518} 519 520 521解决正则 /g 全局匹配替换问题 522我要用 JS 替换一个多行文本的关键字 523正常,没有变量的时候应该是这样: 524把 a 替换成 b: 525string.replace("a","b"); 526以上只能替换第一个匹配的,要全文匹配应该用正则表达式: 527string.replace(/a/g,"b"); 528正则加个参数 g ,表示全文匹配。 529 530但现在,我要替换的不是 a 这个字符了,而是从外面传进来的一个变量: 531var key; 532我可以这么写: 533string.replace(key,"b"); 534这只能替换第一个匹配的,要全文匹配就遇到难题了: 535string.replace(/key/g,"b"); 536这样写是不行的,变量 key 传不到正则里面去。。。头疼啊 537 538解决方法: 539string.replace(new RegExp(key,'g'),"b"); 540 541例子 542var text = "饿~,23333。饿~,测试yongde" 543 var word = "饿~" 544 var newWorld = "额~~eeeee" 545 // text = text.replace(word, newWorld)// 只能替换第一个 546 text = text.replace(new RegExp(word, 'g'), newWorld); // 全局替换 547 console.log(text,'我是text') 548 549 550正则判断是否存在某个特定字符串的方法 551var handleBaseApi = function() { 552 var host = location.host 553 var regDev = RegExp(/gowanme/) 554 var regPro = RegExp(/gowan8/) 555 if (regDev.test(host)) { 556 baseApi = 'http://game.gowanme.com/' 557 } else if (regPro.test(host)) { 558 baseApi = 'http://game.gowan8.com/' 559 } 560} 561handleBaseApi() 562 563 564 565vue 传值赋值 566 this.$router.push({name: 'vipDetails', query: {data: JSON.stringify(obj)}}) 567 this.imgSrc = JSON.parse(this.$route.query.data).detailsSrc 568 569路由跳转有r,获取连接参数没有r 570 571微信跳转问题 572微信下不能用window.open('....'); 573能用location.href = ''; 574 575 576 577 578/** 579 * 封装ajax请求 580 * @param {} option字段 581 * url 582 * data 583 * method 584 * success 585 * error 586 */ 587var requestApi = function (option = {}) { 588 589 var defaults = { 590 method: 'POST', 591 data: {}, 592 success: function (data) { 593 594 }, 595 error: function (status) { 596 597 }, 598 dataType: 'json', 599 async: true 600 } 601 var option = __assign(defaults, option); 602 option.method = option.method.toUpperCase() 603 var formData = [] 604 for (var key in option.data) { 605 formData.push(''.concat(key, '=', option.data[key])) 606 } 607 option.data = formData.join('&') 608 609 var xhr = new XMLHttpRequest() 610 xhr.onreadystatechange = function () { 611 if (xhr.readyState === 4 && xhr.status === 200) { 612 let data = xhr.responseText 613 try { 614 if (option.dataType == 'json') { 615 data = JSON.parse(data) 616 } 617 option.success(data) 618 } catch (e) { 619 console.log(logObj(e), '===>ajax错误信息') 620 option.error(xhr.status) 621 } 622 } else { 623 option.error(xhr.status) 624 } 625 } 626 xhr.open(option.method, option.url, option.async) 627 if (option.method === 'POST') { 628 xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8') 629 } else { 630 option.url = option.url + (option.url.indexOf('?') >= 0 ? "&" : "?") + option.data 631 } 632 xhr.send(option.method === 'POST' ? option.data : null) 633} 634 635 636 637//封装jsonp请求 638function jsonp(obj) { 639 640 var defaults = { 641 data: {}, 642 success: function (data) {}, 643 error: function () {}, 644 timeout: 10000 645 } 646 obj.data = obj.data || ''; 647 if (typeof obj.data == 'object') { 648 var arr = new Array(); 649 for (var key in obj.data) { 650 arr.push(key + '=' + obj.data[key]) 651 } 652 obj.data = arr.join('&'); 653 } 654 let clearJsonp = function (id) { 655 window[id] = undefined; 656 } 657 let removeScript = function (id) { 658 document.body.removeChild(document.getElementById(id)); 659 } 660 var obj = __assign(defaults, obj); 661 //写入url地址中的函数名称,动态创建 662 var id = 'jsonp_' + Date.now() + Math.random().toString().substr(2, 5); 663 664 //创建一个script标签 665 var script = document.createElement("script"); 666 script.id = id; 667 668 //设置标签的请求路径 669 //像这样:http://localhost:3000/api?callback=jsonp_callback_153498520409635392&id=1 670 script.src = obj.url + (/\?/.test(obj.url) ? '&' : '?') + 'callback=' + id + '&' + obj.data; 671 672 var timeoutId = setTimeout(function () { 673 clearJsonp(id); 674 removeScript(id); 675 obj.error(); 676 }, obj.timeout); 677 678 //将创建好的带请求的script标签添加到html的body中 679 document.body.appendChild(script); 680 681 //这里必须这样写window[callbackName]; 682 //如果写window.callbackName会报错没有定义 683 window[id] = function (res) { 684 obj.success(res); 685 //删除的时候可以这样写 686 //由于请求一次会创建一个script标签和一个函数,所以每次获取到结果后就删除 687 clearTimeout(timeoutId); 688 clearJsonp(id); 689 removeScript(id); 690 } 691} 692 693 694用法: 695jsonp({ 696url:'xx', 697data:{}, 698success:function(res){ 699console.log(res,'后端的返回值') 700} 701}) 702 703 704 705 706 707 708 709 710 711/** 712 * 分割IP地址 713 * 714 * @param {} 715 * ipAddress 716 */ 717function getIpNum(ipAddress) { 718 var ip = ipAddress.split("."); 719 var a = parseInt(ip[0]); 720 var b = parseInt(ip[1]); 721 var c = parseInt(ip[2]); 722 var d = parseInt(ip[3]); 723 var ipNum = a * 256 * 256 * 256 + b * 256 * 256 + c * 256 + d; 724 return ipNum; 725} 726 727/** 728 * 判断IP大小 729 */ 730function decideIp(startIp, endIp) { 731 var ip1 = getIpNum(startIp); 732 var ip2 = getIpNum(endIp); 733 return (ip2 > ip1) ? true : false; 734} 735 736 737/******************************************************************************* 738 * openWindow(url)函数:弹出窗口 * url:路径 * left:左边的距离 * top:上边的距离 * width:窗口宽度 * 739 * height:窗口高度 * resize:yes时可调整窗口大小,no则不可调 * 740 ******************************************************************************/ 741function openWindow(url,width, height, resize) { 742 var mleft = (screen.width - width) / 2; 743 var mtop = (screen.height - height) / 2; 744 window.open(url,"","height=" + height + ",width=" + width 745 + ",location=no,menubar=no,resizable=" + resize 746 + ",scrollbars=yes,status=no,toolbar=no,left=" + mleft 747 + ",top=" + mtop + ""); 748} 749 750function openWindow(url,width, height, resize,scrollbars) { 751 var mleft = (screen.width - width) / 2; 752 var mtop = (screen.height - height) / 2; 753 window.open(url,"","height=" + height + ",width=" + width 754 + ",location=no,menubar=no,resizable=" + resize 755 + ",scrollbars="+scrollbars+",status=no,toolbar=no,left=" + mleft 756 + ",top=" + mtop + ""); 757} 758/** 759 * 760 * @param {} url 761 * @param {} width 762 * @param {} height 763 */ 764function showNewWind(url,width,height){ 765 //alert(url); 766 var showresult = window.showModalDialog(url,window,"dialogWidth="+width+"px;dialogHeight="+height+"px;location=no;status=no;scroll=yes"); 767 return showresult; 768} 769 770/** 771 * 772 * @param {} url 773 * @param {} width 774 * @param {} height 775 */ 776function showNewLessWind(url,width,height){ 777 //alert(url); 778 var showresult = window.showModelessDialog(url,window,"dialogWidth:"+width+"px;location=no;status:no;dialogHeight:"+height+"px"); 779 return showresult; 780} 781 782function decideLeve(source){ 783 var regex=/^[a-zA-Z]{1}$/g; 784 return regex.test(source); 785} 786 787function openBlankWindow(url){ 788 openWindow(url,"650","400","yes"); 789} 790 791 792/** 793 验证身份证号是否正确 794 **/ 795function isCardNo(num){ 796 if(isNaN(num)){ 797 alert("输入的身份证号不是数字!"); 798 return false; 799 } 800 var len = num.length; 801 if(len<15 || len>18){ 802 alert("输入的身份证号码长度不正确定!应为15位或18位"); 803 return false; 804 } 805 var re15 = /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$/; 806 var re18 = /^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{4}$/; 807 var res = (re15.test(num) || re18.test(num)); 808 if(res==false){ 809 alert("输入的身份证号格式不正确!"); 810 return false; 811 } 812 return res; 813} 814 815 816 817 818 819 820/** 821 生成指定位数的随机整数 822 **/ 823function getRandomNum(count){ 824 var arr = new Array; 825 var reNum = ""; 826 for(var i=0;i<count;i++){ 827 arr[i] = parseInt(Math.random()*10); 828 reNum += String(arr[i]); 829 } 830 return reNum; 831} 832function random(min,max){ 833 return Math.floor(min+Math.random()*(max-min)); 834} 835 836 837/* 838 *判断包含关系 839 *string:原始字符串 840 *substr:子字符串 841 *isIgnoreCase:忽略大小写 842 */ 843function jsContains(string,substr,isIgnoreCase) 844{ 845 if(isIgnoreCase) 846 { 847 string=string.toLowerCase(); 848 substr=substr.toLowerCase(); 849 } 850 var startChar=substr.substring(0,1); 851 var strLen=substr.length; 852 for(var j=0;j<string.length-strLen+1;j++) 853 { 854 if(string.charAt(j)==startChar)//如果匹配起始字符,开始查找 855 { 856 if(string.substring(j,j+strLen)==substr)//如果从j开始的字符与str匹配,那ok 857 { 858 return true; 859 } 860 } 861 } 862 return false; 863} 864 865/** 866 * 随机数UUID 867 * @return 868 */ 869function makeUUID() { 870 var S4 = function () { 871 return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1); 872 }; 873 //return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4()); 874 return (S4() + S4() + S4() + S4() + S4() + S4() + S4() + S4()); 875} 876 877 878 879 880 881 882/** 883 * 显示提示信息 884 * @param {Object} msg 885 */ 886function showInfoMessage(msg) { 887 Ext.MessageBox.show({ 888 width:320, 889 buttons:Ext.Msg.OK, 890 msg:msg, 891 icon:Ext.MessageBox.INFO, 892 title:"系统提示" 893 }); 894} 895 896/** 897 * 给URL追加参数 898 * @param {} url 899 * @param {} parameter 参数名 900 * @param {} value 参数值 901 */ 902function urlAddParmert(url,parameter,value){ 903 var buf = new StringBuffer(); 904 if(!isEmpty(url)){ 905 buf.append(url); 906 if(url.indexOf("?") > -1){ //已经有参数 907 buf.append("&"); 908 }else{ 909 buf.append("?"); 910 } 911 buf.append(parameter); 912 buf.append("="); 913 buf.append(value); 914 } 915 return buf.toString(); 916} 917 918/** 919 * 得到文件的扩展名 920 * @param {} filename 921 */ 922function getFileExt(filename){ 923 var d=/\.[^\.]+$/.exec(filename); 924 var ext = new String(d); 925 var s = ext.toLowerCase(); 926 return s; 927} 928 929 930//字符串编码 931function strEncode(source){ 932 return encodeURIComponent(source); 933} 934 935//字符串解码 936function strDencode(source){ 937 return decodeURIComponent(source); 938} 939 940 941 942 943 944 945 946 947监控路由 948 watch: { 949 $route: function(to, from) { 950 // 拿到目标参数 to.query.id 去再次请求数据接口 951 // console.log(to, from, 'from') 952 this.proData.article_type = to.query.article_type 953 this.proData.article_id = to.query.article_id 954 this.get() 955 } 956 }, 957 958 959 960 // 基于服务器时间的倒计时-- 961注意 1 nowtime需要设置为全局变量,2 isGetTime 表示是否得到了服务器时间 962 // 处理服务器时间 963 handletime(time) { 964 if (this.data.isGetTime) { 965 return this.data.nowtime += 1000 966 } else { 967 this.data.nowtime = new Date(time).getTime() 968 this.data.isGetTime = true 969 return this.data.nowtime 970 } 971 }, 972 973 // 倒计时 974 countdown: function () { 975 var nowtime = this.handletime("2020/10/8"), 976 endtime = new Date("2020/10/28"); //定义结束时间 977 978 var lefttime = endtime.getTime() - nowtime, //距离结束时间的毫秒数 979 leftd = Math.floor(lefttime / (1000 * 60 * 60 * 24)), //计算天数 980 lefth = Math.floor(lefttime / (1000 * 60 * 60) % 24), //计算小时数 981 leftm = Math.floor(lefttime / (1000 * 60) % 60), //计算分钟数 982 lefts = Math.floor(lefttime / 1000 % 60); //计算秒数 983 leftd = leftd < 10 ? '0' + leftd : leftd 984 lefth = lefth < 10 ? '0' + lefth : lefth 985 leftm = leftm < 10 ? '0' + leftm : leftm 986 lefts = lefts < 10 ? '0' + lefts : lefts 987 return { 988 leftd, 989 lefth, 990 leftm, 991 lefts 992 } 993 }, 994 995 996setInterval(() => { 997 var time = this.countdown() 998 this.setData({ 999 timeObj: time 1000 }) 1001 }, 1000) 1002 1003 1004 1005基于本地时间的倒计时 1006var showtime = function () { 1007 var nowtime = new Date(), //获取当前时间 1008 endtime = new Date("2020/8/8"); //定义结束时间 1009 var lefttime = endtime.getTime() - nowtime.getTime(), //距离结束时间的毫秒数 1010 leftd = Math.floor(lefttime/(1000*60*60*24)), //计算天数 1011 lefth = Math.floor(lefttime/(1000*60*60)%24), //计算小时数 1012 leftm = Math.floor(lefttime/(1000*60)%60), //计算分钟数 1013 lefts = Math.floor(lefttime/1000%60); //计算秒数 1014 return leftd + "天" + lefth + ":" + leftm + ":" + lefts; //返回倒计时的字符串 1015} 1016 1017var div = document.getElementById("showtime"); 1018setInterval (function () { 1019 div.innerHTML = showtime(); 1020}, 1000); //反复执行函数本身 1021 1022 1023 1024验证码倒计时的实现 1025dom: 1026 <span v-show="show" @click="getCode" class="code-txt">获取验证码</span> 1027 <span v-show="!show" class="code-txt count">{{count}} 秒</span> 1028 1029data: 1030 show: true, 1031 count: '', 1032 timer: '' 1033 1034methods: 1035 // 获取验证码 1036 getCode () { 1037 const TIME_COUNT = 60 1038 if (!this.timer) { 1039 this.count = TIME_COUNT 1040 this.show = false 1041 this.timer = setInterval(() => { 1042 if (this.count > 0 && this.count <= TIME_COUNT) { 1043 this.count-- 1044 } else { 1045 this.show = true 1046 clearInterval(this.timer) 1047 this.timer = null 1048 } 1049 }, 1000) 1050 } 1051 }, 1052 1053 1054数组map方法 1055 1056 map() 方法返回一个由原数组中的每个元素调用一个指定方法后的返回值组成的新数组。 1057 1058 1059 1060// 原生js实现复制内容到剪切板,兼容pc、移动端(支持Safari浏览器) 1061 copyText () { 1062 if (typeof document.execCommand !== 'function') { 1063 FN.showMsg('复制失败') 1064 return 1065 } 1066 if (!document.createRange) { 1067 // pc,安卓 1068 var dom = document.getElementById('copy-qq') 1069 dom.select() 1070 var result = document.execCommand('copy') 1071 if (result) { 1072 FN.showMsg('复制成功') 1073 } 1074 } else { 1075 // 苹果端 1076 var range = document.createRange() 1077 var idom = document.getElementById('copy-qq') 1078 range.selectNode(idom) 1079 const selection = window.getSelection() 1080 if (selection.rangeCount > 0) { 1081 selection.removeAllRanges() 1082 } 1083 selection.addRange(range) 1084 document.execCommand('copy') 1085 FN.showMsg('复制成功') 1086 } 1087 } 1088 1089 1090提取字符串中的数字 1091var s ="价格4500元"; 1092var num= s.replace(/[^0-9]/ig,""); 1093alert(num);//4500 1094 1095 1096vue中需要给element的函数,添加参数时,可以使用bind进行绑定添加 1097 1098 1099 1100
点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

皕杰报表之UUID

​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

一篇文章带你了解JavaScript日期

日期对象允许您使用日期(年、月、日、小时、分钟、秒和毫秒)。一、JavaScript的日期格式一个JavaScript日期可以写为一个字符串:ThuFeb02201909:59:51GMT0800(中国标准时间)或者是一个数字:1486000791164写数字的日期,指定的毫秒数自1970年1月1日00:00:00到现在。1\.显示日期使用

2020年前端实用代码段,为你的工作保驾护航

有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )