• js常用共同方法


    var uh_rdsp = (function(){
        
        //获取根目录
        var getContextPath = function(){
            var pathName = document.location.pathname;
            var index = pathName.substr(1).indexOf("/");
            var result = pathName.substr(0,index+1);
            return result;
        }
        
        //如果传入的没有参数 则显示迷你指示器 如果第一个参数传入null  并且有第二个参数 
        //则在指定时间之后关闭迷你指示器
        //显示等待框 如果只传入一个参数 则默认为显示内容 
        //如果传入多个参数  第二个参数则是默认显示多长时间
        var showWait = (function(){
            var showModal = function(message){
                $.showPreloader(message);
            }
            var showIndicator = function(){
                $.showIndicator();
            }
            var hideModal = function(){
                $.hidePreloader();
            }
            var hideIndicator = function(){
                $.hideIndicator();
            }
            return function(){
                if(arguments[0] == 'show'){
                    if(arguments[1] != null){
                        showModal(arguments[1]);
                    }else{
                        showIndicator();
                    }
                    if(arguments.length > 2){
                        if(arguments[1] != null){
                            setTimeout(function(){
                                hideModal();
                            },arguments[2]);
                        }else{
                            setTimeout(function(){
                                hideIndicator();
                            },arguments[2]);
                        }
                    }
                }
                if(arguments[0] == 'hide'){
                    if(arguments[1] == 'modal'){
                        hideModal();
                    }
                    if(arguments[1] == 'indi'){
                        hideIndicator();
                    }
                }
            }
        })();
        
        //显示Toast 传入2个参数 第一个参数为显示内容  第二个参数为显示时间 默认2秒
        var showToast = (function(){
            var showToast = function(){
                if(arguments.length == 2){
                    $.toast(arguments[0],arguments[1]);
                }else{
                    $.toast(arguments[0]);
                }
                
            }
            
            return function(){
                showToast.apply(null,arguments);
            }
        })();
        //显示alert 可传入1个参数 显示内容
        var showAlert = (function(){
            var alertMsg = function(){
                $.alert(arguments[0]);
            }
            return function(){
                alertMsg.apply(null,arguments)
            }
        })();
        
        //显示确认框 传入两个参数 第一个为显示信息  第二个为点击确认后的回调函数
        var showConfirm = (function(){
            var confirmMsg = function(){
                if(arguments.length == 1){
                    $.confirm(arguments[0]);    
                }
                if(arguments.length == 2){
                    $.confirm(arguments[0],arguments[1]);
                }
            }
            return function(){
                confirmMsg.apply(null,arguments);
            }
        })();
        
        //显示操作表 传入两个参数 第一个参数为数组 表示显示内容 第二个参数为回调方法 
        var showActions = (function(){
            var cache = {};
            var actions = function(){
                var buttons1 = [];
                for (var i = 0,l=arguments[0].length;i < l;i++) {
                    buttons1.push({text:arguments[0][i].text,onClick:arguments[0][i].onclick});
                }
                var buttons2 = [{text:'取消'}];
                var groups = [buttons1, buttons2];
                $.actions(groups);
            }
            return function(){
                actions.apply(null,arguments);
            }
        })();
        //显示日期选择控件
        var showDatePicker = (function(){
            var cache = {};
            var showDateFun = function(){
                var id = arguments[0];
                var showdate = arguments[1];
                id.calendar({value:[showdate],minDate:showdate});
            }
            return function(){
                if(arguments[0].id in cache){
                    return ;
                }
                cache[arguments[0].id] = arguments[0];
                showDateFun.apply(null,arguments);
            }
        })();
        
        //parse
        var parseTemplate = function(dta,tmpl){
            var format = {
                name : function(x) {
                    if(x == null || x == "null"){
                        return "";
                    }
                    return x;
                }
            };
            return tmpl.replace(/{(w+)}/g, function(m1, m2) {
                if (!m2 && m2!= "null")
                    return "";
                return (format && format[m2]) ? format[m2](dta[m2]) : dta[m2];
            });
        };
        //ajax 请求前置方法
        $(document).on('ajaxBeforeSend', function(e, xhr, options){
          xhr.setRequestHeader('Authorization',"UH_RDSP_tok"+$('#token').val());
        });
        //发送ajax请求 传入3个参数 url:请求地址 params:请求参数 callback:回调方法
        var ajaxUrl = (function(){
            var count   = 1;
            var timer ;
            var isFirst = true;
            var ajaxfun = function(){
                var url = arguments[0];
                var params = arguments[1];
                var str = JSON.stringify(params);  
                var callback = arguments[2];
                $.ajax({
                      type: 'POST',
                      url: getContextPath()+url,
                      data: params,
                      dataType: 'json',
                      context: $('body'),
                      success: function(data){
                          callback(data);
                          count++;
                      },
                      error: function(xhr, type){
                        showAlert('请求异常');
                      }
                })
            }
            return function(){
                var args = arguments;
    //            if(isFirst){
    //                
    //                return isFirst = false;
    //            }
                ajaxfun.apply(null,arguments);
    //            if(timer){
    //                showToast('操作过于频繁,请稍后',1000);
    //                return false;
    //            }
    //            timer = setTimeout(function(){
    //                clearTimeout(timer);
    //                timer = null;
    //                ajaxfun.apply(null,args);
    //            },2000);
            }
        })();
        //发送post请求 传入2个参数 url:请求地址 params:请求参数 
        var postUrl = (function(){
            var timer;
            var isFirst = true;
            var postFun = function(){
                var url = arguments[0];
                var params = arguments[1];
                var temp = document.createElement("form");        
                temp.action = url;        
                temp.method = "post";        
                temp.style.display = "none";        
                for (var x in params) {        
                    var opt = document.createElement("textarea");        
                    opt.name = x;        
                    opt.value = params[x];        
                    // alert(opt.name)        
                    temp.appendChild(opt);        
                }
                var opt = document.createElement("textarea");
                opt.name = 'token';
                opt.value = "UH_RDSP_tok"+$('#token').val();
                temp.appendChild(opt);   
                document.body.appendChild(temp);        
                temp.submit();  
            }
            return function(){
                var args = arguments;
                if(isFirst){
                    postFun.apply(null,arguments);
                    return isFirst = false;
                }
                if(timer){
                    showToast('操作过于频繁,请稍后',1000);
                    return false;
                }
                timer = setTimeout(function(){
                    clearTimeout(timer);
                    timer = null;
                    postFun.apply(null,args);
                },2000);
            }
                  
        })();
        //函数截流 传入调用方法 以及延迟时间 在调用方法之后 延迟时间之后才会继续调用方法
        var throttle = function(fn,interval){
            var _self = fn,
            timer,
            firstTime = true;
            return function(){
                var args = arguments,
                _me = this;
                if(firstTime){
                    _self.apply(_me,args);
                    return firstTime = false;
                }
                if(timer){
                    showToast('操作过于频繁,请稍后',1000);
                    return false;
                }
                timer = setTimeout(function(){
                    clearTimeout(timer);
                    timer = null;
                    _self.apply(_me,args);
                },interval||2000);
            }
        };
        //每隔200毫秒执行一次方法 每次执行count个
        var timeChunk = function(ary,fn,count){
            var obj,t;
            var len = ary.length;
            var start = function(){
                for (var i = 0; i < Math.min(count||1,ary.length); i++) {
                    var obj = ary.shift();
                    fn(obj);
                }
            }
            return function(){
                t = setInterval(function(){
                    if(ary.length === 0){
                        return clearInterval(t);
                    }
                    start();
                },200);
            }
        }
        
        var sendparams = {};
        var loading = false;
        // 最多可加载的条目
        var maxItems = 200;
        // 每次加载添加多少条目
        var itemsPerLoad = 10;
        // 上次加载的序号
        var lastIndex = 0;
        var count = 1;
        var pullDownRefresh = function(url,params,callback){
            sendparams = params;
            $(document).on('refresh', '.pull-to-refresh-content',function(e) {
                callback(url,sendparams,1);
                count = 1;
            });
        }
        var pullUpRefresh = function(url,params,callback){
            lastIndex = 0;
            count = 1;
                 $(document).on('infinite', '.infinite-scroll-bottom',function() {
                  // 如果正在加载,则退出
                  if (loading) return;
                  // 设置flag
                  loading = true;
                  var url = arguments[0];
                  sendparams = arguments[1];
                  var callback = arguments[2];
                 
                  if (lastIndex >= maxItems) {
                      // 加载完毕,则注销无限加载事件,以防不必要的加载
                      $.detachInfiniteScroll($('.infinite-scroll'));
                      // 删除加载提示符
                      $('.infinite-scroll-preloader').remove();
                      return;
                  }
                  var total = callback(url,sendparams,count);
                  count++;
                  maxItems = total;
                  // 更新最后加载的序号
                  lastIndex = $('.list-container').children().length;
                  //容器发生改变,如果是js滚动,需要刷新滚动
                  $.refreshScroller();
                   // 重置加载flag
                  loading = false;
                  
              });
        }
        
        //获取明天日期 并以YYYY-MM-DD格式化
        var getNowDate = function(){
            var date = new Date();
            date = new Date((date/1000+86400)*1000);
            var seperator1 = "-";
            var seperator2 = ":";
            var year = date.getFullYear();
            var month = date.getMonth() + 1;
            var strDate = date.getDate();
            if (month >= 1 && month <= 9) {
                month = "0" + month;
            }
            if (strDate >= 0 && strDate <= 9) {
                strDate = "0" + strDate;
            }
    //        var currentdate = year + seperator1 + month + seperator1 + strDate
    //                + " " + date.getHours() + seperator2 + date.getMinutes()
    //                + seperator2 + date.getSeconds();
            var currentdate = year + seperator1 + month + seperator1 + strDate;
                    
            return currentdate;
        }
        
        function hasClass(obj, cls) {
            return obj.className.match(new RegExp('(\s|^)' + cls + '(\s|$)'));
        }
        
        function removeClass(obj, cls) {
            if (hasClass(obj, cls)) {
                var reg = new RegExp('(\s|^)' + cls + '(\s|$)');
                obj.className = obj.className.replace(reg, ' ');
            }
        }
        function addClass(obj, cls) {
            if (!hasClass(obj, cls)) {
                obj.className += " " + cls;
            }
        }
        //传入两个参数  1.show或者hide  2.callback 城市点击回调方法
        var showCitys = (function(){
            var isFirst = true;
            var showCity = function(){
                document.getElementById("bg").style.display ="block";
                document.getElementById("show").style.display ="block";
            }
            var hideCity = function(){
                document.getElementById("bg").style.display ='none';
                document.getElementById("show").style.display ='none';
            };
            
            var createCity = function(){
                var cityshtml = '<div id="bg"></div><div id="show"><div><!--当前城市--><div class="citys_top uh_rdsp_white_background">当前城市:<img id="citysclose"src="../images/Item_Clost.png"class="pull-right"style=" 20px;margin-right: 20px;"/></div><!--城市列表--><div class="uh_rdsp_white_background"><div class="row city_button_parentdiv"><hr class="text_titleshow_hrs"><div class="col-33 city_button_div"><input type="button"class="city_button_selected city_button_content"value="全省"/></div><div class="col-33 city_button_div"><input type="button"class="city_button city_button_content"value="太原市"/></div><div class="col-33 city_button_div"><input type="button"class="city_button city_button_content"value="大同市"/></div></div><div class="row city_button_parentdiv"><div class="col-33 city_button_div"><input type="button"class="city_button city_button_content"value="阳泉市"/></div><div class="col-33 city_button_div"><input type="button"class="city_button city_button_content"value="长治市"/></div><div class="col-33 city_button_div"><input type="button"class="city_button city_button_content"value="晋城市"/></div></div><div class="row city_button_parentdiv"><div class="col-33 city_button_div"><input type="button"class="city_button city_button_content"value="朔州市"/></div><div class="col-33 city_button_div"><input type="button"class="city_button city_button_content"value="忻州市"/></div><div class="col-33 city_button_div"><input type="button"class="city_button city_button_content"value="晋中市"/></div></div><div class="row city_button_parentdiv"><div class="col-33 city_button_div"><input type="button"class="city_button city_button_content"value="临汾市"/></div><div class="col-33 city_button_div"><input type="button"class="city_button city_button_content"value="吕梁市"/></div><div class="col-33 city_button_div"><input type="button"class="city_button city_button_content"value="运城市"/></div></div><div class="uh_rdsp_white_background city_bottom"id="citys_bottom">确&nbsp;&nbsp;&nbsp;&nbsp;定</div></div><!--作者:123366176@qq.com时间:2016-08-02描述:确定按钮--></div></div>';
                $('#htmlbody').append(cityshtml);
                var citys = document.getElementsByClassName('city_button_content');
                var callback = arguments[1];
                var selectedcityname = '全省';
                var selectedcityid   = '';
                document.getElementById("bg").style.display ="block";
                document.getElementById("show").style.display ="block";
                document.getElementById('citysclose').onclick = hideCity;
                document.getElementById('citys_bottom').onclick = function(){
                        callback(selectedcityname,selectedcityid);
                        hideCity();
                };
                
                var cleanAll = function(){
                        for(var i = 0;i < citys.length;i++){
                            removeClass(citys[i],'city_button_selected');
                            addClass(citys[i],'city_button')
                        }
                }
                for(var i = 0;i < citys.length;i++){
                       (function(i){
                           citys[i].onclick = function(){
                               cleanAll.call();
                               if(citys[i].value == '全省'){
                                   selectedcityname = '全省';
                                   selectedcityid = '';
                                   removeClass(citys[i],'city_button');
                                   addClass(citys[i],'city_button_selected');    
                               }else if(citys[i].value == '太原市'){
                                   selectedcityname = '太原市';
                                   selectedcityid = '1401';
                                   removeClass(citys[i],'city_button');
                                   addClass(citys[i],'city_button_selected');        
                                   //callback.call(null,citys[i].value,1401);
                               }else if(citys[i].value == '大同市'){
                                   selectedcityname = '大同市';
                                   selectedcityid = '1402';
                                   removeClass(citys[i],'city_button');
                                   addClass(citys[i],'city_button_selected');    
                                   //callback.call(null,citys[i].value,1402);
                               }else if(citys[i].value == '阳泉市'){
                                   selectedcityname = '阳泉市';
                                   selectedcityid = '1403';
                                   removeClass(citys[i],'city_button');
                                   addClass(citys[i],'city_button_selected');    
                                   //callback.call(null,citys[i].value,1403);
                               }else if(citys[i].value == '长治市'){
                                   selectedcityname = '长治市';
                                   selectedcityid = '1404';
                                   removeClass(citys[i],'city_button');
                                   addClass(citys[i],'city_button_selected');    
                                   //callback.call(null,citys[i].value,1404);
                               }else if(citys[i].value == '晋城市'){
                                   selectedcityname = '晋城市';
                                   selectedcityid = '1405';
                                   removeClass(citys[i],'city_button');
                                   addClass(citys[i],'city_button_selected');    
                                   //callback.call(null,citys[i].value,1405);
                               }else if(citys[i].value == '朔州市'){
                                   selectedcityname = '朔州市';
                                   selectedcityid = '1406';
                                   removeClass(citys[i],'city_button');
                                   addClass(citys[i],'city_button_selected');    
                                   //callback.call(null,citys[i].value,1406);
                               }else if(citys[i].value == '忻州市'){
                                   selectedcityname = '忻州市';
                                   selectedcityid = '1407';
                                   removeClass(citys[i],'city_button');
                                   addClass(citys[i],'city_button_selected');    
                                   //callback.call(null,citys[i].value,1407);
                               }else if(citys[i].value == '晋中市'){
                                   selectedcityname = '晋中市';
                                   selectedcityid = '1408';
                                   removeClass(citys[i],'city_button');
                                   addClass(citys[i],'city_button_selected');    
                                   //callback.call(null,citys[i].value,1408);
                               }else if(citys[i].value == '临汾市'){
                                   selectedcityname = '临汾市';
                                   selectedcityid = '1409';
                                   removeClass(citys[i],'city_button');
                                   addClass(citys[i],'city_button_selected');    
                                   //callback.call(null,citys[i].value,1409);
                               }else if(citys[i].value == '吕梁市'){
                                   selectedcityname = '吕梁市';
                                   selectedcityid = '1410';
                                   removeClass(citys[i],'city_button');
                                   addClass(citys[i],'city_button_selected');    
                                   //callback.call(null,citys[i].value,1410);
                               }else if(citys[i].value == '运城市'){
                                   selectedcityname = '运城市';
                                   selectedcityid = '1411';
                                   removeClass(citys[i],'city_button');
                                   addClass(citys[i],'city_button_selected');    
                                   //callback.call(null,citys[i].value,1411);
                               }
                               
                           }
                       })(i,callback,cleanAll,selectedcityname,selectedcityid)
                   
                   }
            };
            return function(){
                if(arguments.length == 0){
                    return ;
                }
                if(isFirst == true && arguments[0] == 'show'){
                    createCity.apply(null,arguments);
                    isFirst = false;
                    return ;
                }
                if(arguments[0] == 'hide'){
                    hideCity.apply(null,arguments);
                    return ;
                }
                if(arguments[0] == 'show'){
                    showCity.apply(null,arguments);
                    return ;
                }
            }
            
            
        })();
        
        var ajaxUrlPath = (function(){
            var count   = 1;
            var timer ;
            var isFirst = true;
            var ajaxfun = function(){
                var url = arguments[0];
                var params = arguments[1];
                var str = JSON.stringify(params);  
                var callback = arguments[2];
                $.ajax({
                      type: 'POST',
                      url: $('#contextPath').val()+url,
                      data: params,
                      dataType: 'json',
                      context: $('body'),
                      success: function(data){
                          callback(data);
                          count++;
                      },
                      error: function(xhr, type){
                        showAlert('请求异常');
                      }
                })
            }
            return function(){
                var args = arguments;
                if(isFirst){
                    ajaxfun.apply(null,arguments);
                    return isFirst = false;
                }
                if(timer){
                    showToast('操作过于频繁,请稍后',1000);
                    return false;
                }
                timer = setTimeout(function(){
                    clearTimeout(timer);
                    timer = null;
                    ajaxfun.apply(null,args);
                },2000);
            }
        })();
        
        return {
            getContextPath : getContextPath,
            showWait: showWait,
            showToast:showToast,
            showAlert:showAlert,
            showConfirm:showConfirm,
            showActions:showActions,
            showDatePicker:showDatePicker,
            postUrl:postUrl,
            ajaxUrl:ajaxUrl,
            throttle:throttle,
            getNowDate:getNowDate,
            showCitys:showCitys,
            removeClass:removeClass,
            addClass:addClass,
            pullUpRefresh:pullUpRefresh,
            pullDownRefresh:pullDownRefresh,
            parseTemplate:parseTemplate,
            ajaxUrlPath:ajaxUrlPath
        };
    })();
  • 相关阅读:
    2019/1/17 break语句小练习
    2019/1/17goto语句小试牛刀
    python 中* 和**的作用
    python 元组编码和解码问题
    python SMTP 发送邮件
    python 自定义异常
    python websocket client 使用
    excel、xls文件读写操作
    windows10局域网实现文件共享
    django入门
  • 原文地址:https://www.cnblogs.com/holdon521/p/6473498.html
Copyright © 2020-2023  润新知