一個前端框架應該有的一些公共函數

?一、防止ie瀏覽器按backspace回退頁面

//防止后退返回頁面,如果非文本框、密碼框、文本域控件,或控件非可用裝填,則禁用后退按鍵
var ua=navigator.userAgent.toLowerCase(); 
var isIE=ua.indexOf("msie")>-1;
window.document.onkeydown =function(e){var e = e;var obj;        //事件源var t;            //控件類型var keyCode;    //按鍵ascii碼if(isIE){e = event || window.event;keyCode = e.keyCode;}else{keyCode = e.keyCode || e.which;if(keyCode==undefined||keyCode==null||keyCode==''){keyCode=String.fromCharCode(e.charCode);}}obj = e.target || e.srcElement; //獲取事件源 t = obj.type || obj.getAttribute('type'); if (e.keyCode==8 && (obj.readOnly || obj.disabled || (t != "password" && t != "text" && t != "textarea" && obj.tagName!=='INPUT'))) {return false;}
};

?

二、獲取頁面傳參?

// 獲取參數
var name = window.location.search; //獲取?后面的字符串
function getUrlParam(name) {var urlArr = [],urlObj={};name = decodeURI(name);urlArr=name.substring(1).split('&');for(var i =0;i<urlArr.length;i++){var valueArr=urlArr[i].split('=');urlObj[valueArr[0]]=valueArr[1];}return urlObj; }

?

三、加載動畫(避免重復點擊機制),初始化ajax(以jquery為例)

 1 jQuery.bootstrapLoading = {
 2     start: function (options) {
 3         var defaults = {
 4             opacity: 1,
 5             //loading頁面透明度
 6             backgroundColor: "rgba(0,0,0,0.3)",
 7             //loading頁面背景色
 8             borderColor: "#bbb",
 9             //提示邊框顏色
10             borderWidth: 0,
11             //提示邊框寬度
12             borderStyle: "solid",
13             //提示邊框樣式
14             loadingTips: "",
15             //提示文本
16             TipsColor: "#666",
17             //提示顏色
18             delayTime: 1000,
19             //頁面加載完成后,加載頁面漸出速度
20             zindex: 99999999,
21             //loading頁面層次
22             sleep: 0,
23             //設置掛起,等于0時則無需掛起
24             width: '150px',
25             height: '165px',
26         }
27         var options = $.extend(defaults, options);
28 
29         //獲取頁面寬高
30         var _PageHeight = document.documentElement.clientHeight,
31         _PageWidth = document.documentElement.clientWidth;
32         //獲取頁面路徑
33         var baseUrl = window.document.location.protocol + "//" + window.document.location.host + "/";
34           var shortenedUrl = window.document.location.href.replace(baseUrl, "").replace(/\/\//g, "/").replace("//", "/");
35           if(shortenedUrl.startsWith("/")){
36               shortenedUrl = shortenedUrl.substring(1);
37           }
38           if(shortenedUrl.indexOf("web/")==0){
39               baseUrl = baseUrl + shortenedUrl.substring(0, shortenedUrl.indexOf("/"));
40           }
41         //在頁面未加載完畢之前顯示的loading Html自定義內容
42         var _LoadingHtml = '<div id="loadingPage" style="position:fixed;left:0;top:0;_position: absolute;width:100%;height:' + _PageHeight + 'px;background:' + options.backgroundColor + ';opacity:' + options.opacity + ';filter:alpha(opacity=' + options.opacity * 100 + ');z-index:' + options.zindex + 
43         ';"><div id="loadingTips" class="loadingTips" style="position: absolute; cursor1: wait; border-color:' + options.borderColor + 
44         ';background-position:50%; width: '+options.width+';height:'+options.height+';border-style:' + options.borderStyle + ';border-width:' + options.borderWidth + 'px; line-height:80px; padding: 15px;border-radius:10px;  background: url('+baseUrl+'/images/loading.gif) no-repeat center; color:' + options.TipsColor + ';font-size:20px;">' 
45         + options.loadingTips + '</div></div>';
46 
47         //呈現loading效果
48         $("body").append(_LoadingHtml);
49         //獲取loading提示框寬高
50         var _LoadingTipsH = document.getElementById("loadingTips").clientHeight,
51         _LoadingTipsW = document.getElementById("loadingTips").clientWidth;
52 
53         //計算距離,讓loading提示框保持在屏幕上下左右居中
54         var _LoadingTop = _PageHeight > _LoadingTipsH ? (_PageHeight - _LoadingTipsH) / 2 : 0,
55         _LoadingLeft = _PageWidth > _LoadingTipsW ? (_PageWidth - _LoadingTipsW) / 2 : 0;
56 
57         $(".loadingTips").css({
58             "left": _LoadingLeft + "px",
59             "top": _LoadingTop + "px"
60         });
61 
62         //監聽頁面加載狀態
63         // document.onreadystatechange = PageLoaded;
64 
65         //當頁面加載完成后執行
66         // function PageLoaded() {
67         //     if (document.readyState == "complete") {
68         //         var loadingMask = $('#loadingPage');
69 
70         //         setTimeout(function () {
71         //             loadingMask.animate({
72         //                 "opacity": 0
73         //             },
74         //             options.delayTime,
75         //             function () {
76         //                 $(this).hide();
77 
78         //             });
79 
80         //         },
81         //         options.sleep);
82 
83         //     }
84         // }
85     },
86     end: function () {
87         $("#loadingPage").remove();
88     }
89 }
90 //初始化ajax
91 $.ajaxSetup({
92     beforeSend:function(xhr){
93         $.bootstrapLoading.start();
94     },
95         complete: function () {
96             $.bootstrapLoading.end();
97         }
98 });

4、時間格式化

Date.prototype.format=function(fmt) {         var o = {         "M+" : this.getMonth()+1, //月份         "d+" : this.getDate(), //"h+" : this.getHours()%12 == 0 ? 12 : this.getHours()%12, //小時         "H+" : this.getHours(), //小時         "m+" : this.getMinutes(), //"s+" : this.getSeconds(), //"q+" : Math.floor((this.getMonth()+3)/3), //季度         "S" : this.getMilliseconds() //毫秒         
    };         var week = {         "0" : "/u65e5",         "1" : "/u4e00",         "2" : "/u4e8c",         "3" : "/u4e09",         "4" : "/u56db",         "5" : "/u4e94",         "6" : "/u516d"        };         if(/(y+)/.test(fmt)){         fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));         }         if(/(E+)/.test(fmt)){         fmt=fmt.replace(RegExp.$1, ((RegExp.$1.length>1) ? (RegExp.$1.length>2 ? "/u661f/u671f" : "/u5468") : "")+week[this.getDay()+""]);         }         for(var k in o){         if(new RegExp("("+ k +")").test(fmt)){         fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));         }         }         return fmt;         
} function getDate(strDate){if(strDate && strDate!=""){var date = eval('new Date(' + strDate.replace(/\d+(?=-[^-]+$)/, function (a) { return parseInt(a, 10) - 1; }).match(/\d+/g) + ')');return date;}return undefined;
}function formatDate(date, fmt){var format = fmt || "yyyy-MM-dd hh:mm:ss";if(date instanceof Date){return date.format(format);}else if(typeof date == 'string'){var d = getDate(date);if(d){return d.format(format);}return '';}else{return date;}
}

?5、格式化數據(樹狀結構)

 1 TreeDataFormat = {
 2     format : function(conf) {
 3         var idField, textField, parentField, iconClsField;
 4         idField = conf.idField ||  'id';
 5         textField = conf.textField || 'text';
 6         parentField = conf.parentField || 'pid';
 7         iconClsField = conf.iconClsField || 'iconCls';
 8         data = conf.data
 9         var i, l, treeData = [], tmpMap = [];
10         for (i = 0, l = data.length; i < l; i++) {
11             data[i]['id'] = data[i][idField];
12             data[i]['text'] = data[i][textField];
13             data[i]['pid'] = data[i][parentField];
14             data[i]['iconCls'] = data[i][iconClsField] || 'anticon icon-nav';
15             data[i]['children'] = [];
16             tmpMap[data[i][idField]] = data[i];
17         }
18         for (i = 0, l = data.length; i < l; i++) {
19             if (tmpMap[data[i][parentField]] && data[i][idField] != data[i][parentField]) {
20                 if (!tmpMap[data[i][parentField]]['children'])
21                     tmpMap[data[i][parentField]]['children'] = [];
22                 data[i][parentField]
23                 data[i]['text'] = data[i][textField];
24                 tmpMap[data[i][parentField]]['children'].push(data[i]);
25             } else {
26                 data[i]['text'] = data[i][textField];
27                 treeData.push(data[i]);
28             }
29         }
30         return treeData;
31     },
32     getChildrenByPid:function(treeData, pidField, pid, result){
33         result = result || [];
34         for (var i = 0; i < treeData.length; i++) {
35             if (treeData[i][pidField] === pid)
36                 result.push(treeData[i]);
37             else {
38                 if (treeData[i].hasOwnProperty("children")) {
39                     result = this.getChildrenByPid(treeData[i].children, pidField, pid, result);
40                 }
41             }
42         }
43         return result;
44     }    
45 }

?

轉載于:https://www.cnblogs.com/cutone/p/7125507.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/540967.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/540967.shtml
英文地址,請注明出處:http://en.pswp.cn/news/540967.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Kruskal(P)和Prim(K)算法

最小生成樹 (Minimum Spanning Tree) An MST is a subset of the edges of the connected, undirected graph that connect all the vertices together, in which there is no forming of a cycle and there should be minimum possible total edge weight. MST是已連接的無向圖…

java get post 注解,GET/POST接收或發送數據的問題

在文章開始&#xff0c;先來回憶一下GET、POST這兩種請求方式的區別。?Http定義了與服務器交互的不同方法&#xff0c;最基本的方法有4種&#xff0c;分別是GET&#xff0c;POST&#xff0c;PUT&#xff0c;DELETE。URL全稱是資源描述符&#xff0c;我們可以這樣認為&#xff…

mybatis中sql語句傳入多個參數方法

1 使用map <select id"selectRole" parameterType"map" resultType"RoleMap">SELECT id, roleName, noteFROM roleWHERE roleName LIKE Concat(%,#{roleName},%)and note like Concat(%,#{note},%)</select> 在接口中如下定義 List&…

kotlin半生對象_Kotlin程序| 隨播對象特征

kotlin半生對象伴侶對象 (Companion object) If you need a function or a property to be tied to a class rather than to instances of it (similar to static in java), you can declare it inside a companion object: 如果需要將函數或屬性綁定到類而不是實例(類似于java…

mysql安裝注意步驟,mysql安裝步驟

mysql安裝步驟1、在官網下載對應的壓縮文件&#xff0c;放到本地文件夾下&#xff0c;解壓縮。2、配置Path環境變量&#xff1a;新增mysql的bin文件夾路徑&#xff0c;C:\software\mysql-8.0.23-winx64\bin。3、在mysql根目錄下新增my.ini配置文件。內容如下&#xff0c;basedi…

maven插件介紹之tomcat7-maven-plugin

tomcat7-maven-plugin插件的pom.xml依賴為&#xff1a; <dependency><groupId>org.apache.tomcat.maven</groupId><artifactId>tomcat7-maven-plugin</artifactId><version>2.2</version> </dependency>一&#xff1a;直接執行…

在Python中模擬do-while循環

Python as a language doesnt support the do-while loop. However, we can have a workaround to emulate the do-while loop. Python作為一種語言不支持do-while循環。 但是&#xff0c;我們可以采用一種變通方法來模擬do-while循環 。 The syntax for do-while is as follo…

織夢cms生成首頁html的php文件,織夢DedeCMS定時自動生成首頁HTML的實現方法

只需要制作一個文件然后在首頁模板添加一句代碼就可以實現讓織夢DedeCMS自動生成首頁html&#xff0c;具體方法如下&#xff1a;第一步、需要在首頁調用隨機文章&#xff0c;這樣每次自動更新才會有更新的效果&#xff0c;隨機文章調用標簽如下&#xff1a;{dede:arclist sortr…

Linux下安裝Flume

1 下載Flume Welcome to Apache Flume — Apache Flume 下載1.9.0版本 2 上傳服務器并解壓安裝 3 刪除lib目錄下的guava-11.0.2.jar &#xff08;如同服務器安裝了hadoop&#xff0c;則刪除&#xff0c;如沒有安裝hadoop則保留這個文件&#xff0c;否則無法啟動flume&#…

Apple新發布的APFS文件系統對用戶意味著什么

2016年WWDC大會上&#xff0c;Apple除了公布watchOS、tvOS、macOS以及iOS等一系列系統和軟件更新外&#xff0c;還公布了一個名為APFS&#xff08;Apple File System&#xff09;的文件系統。 這一全新文件系統專門針對閃存/SSD進行優化&#xff08;但依然可用于傳統機械硬盤&a…

chown –r mysql:mysql,mysql部署,操作及異常處理

1、將mysql-5.1.50-linux-x86_64-glibc23.tar.gz移至/usr/local/目錄下&#xff0c;并改名為mysql增加mysql組#groupadd mysql建mysql用戶&#xff0c;并加入到mysql組中#useradd –g mysql mysql源碼包解壓#tar mysql-5.1.50-linux-x86_64-glibc23.tar.gz將解壓后的源碼包放置…

光伏等新能源信用風險事件頻繁爆發

2016年以來&#xff0c;伴隨著供給側改革相關政策陸續出臺和落地&#xff0c;去產能、去杠桿誘發信用風險事件陸續爆出。而在“11天威NTN1”、“15云峰PPN001”及“15云峰PPN003”等信用風險事件上&#xff0c;大股東“棄車保帥”行為再現&#xff0c;令本就失去造血能力的企業…

ruby array_Ruby中帶有示例的Array.zip()方法

ruby arrayArray.zip()方法 (Array.zip() Method) In this article, we will study about Array.zip() Method. You all must be thinking the method must be doing something which is related to zipping values of the Array instance. It is not as simple as it looks. W…

matlab中迪杰斯特拉算法,dijkstra算法(迪杰斯特拉算法)

單源最短路徑算法——Dijkstra算法&lpar;迪杰斯特拉算法&rpar;一 綜述 Dijkstra算法(迪杰斯特拉算法)主要是用于求解有向圖中單源最短路徑問題.其本質是基于貪心策略的(具體見下文).其基本原理如下: (1)初始化:集合vertex_set初始為{sourc ...Dijkstra【迪杰斯特拉算法…

關于概率算法的問題,不知道邏輯錯在哪里,求debug

做個骰子成功幾率的分析&#xff0c;投n顆骰子&#xff0c;第一次投成功的幾率是a,然后投成功的骰子&#xff0c;需要再投1次&#xff0c;這次成功的幾率是b。第二次成功的骰子才算最終成功。 要分析出n顆骰子&#xff0c;最終成功0到n顆的概率。 我寫了個算法&#xff0c;求出…

tps 交易量_交易處理系統(TPS)

tps 交易量A transaction is a simple process that takes place during business operations. The transaction processing system (TPS) manages the business transactions of the client and therefore helps a companys operations. A TPS registers, as well as all of i…

matlab for循環不覆蓋,將輸出保存到文本文件而不覆蓋和打印矩陣中的N個條目[matlab]...

這是代碼&#xff1a;for i 1:4;fileID fopen(testdata.txt, at);fprintf(fileID, this is answer %d\n,i);fprintf(fileID, %5.3e\n, v{i});fclose(fileID);end在記事本中回答&#xff1a;this is answer 11.000e0001.000e0001.000e0001.000e0001.000e0001.000e0000.000e0001…

(轉)Redis研究(一)—簡介

http://blog.csdn.net/wtyvhreal/article/details/41855327 Redis是一個開源的高性能鍵值對數據庫。它通過提供多種鍵值數據類型來適應不同場景下的存儲需求&#xff0c;并借助許多高層級的接口使其可以勝任如緩存、隊列系統等不同的角色。 1.1歷史和發展 2008年&#xff0c;意…

c bitset get_Java BitSet get()方法與示例

c bitset getBitSet類的get()方法 (BitSet Class get() method) Syntax: 句法&#xff1a; public boolean get(int bit_in);public BitSet get(int st_in, int en_in);get() method is available in java.util package. get()方法在java.util包中可用。 get(int bit_in) meth…

有擾動的閉環傳遞函數 matlab,(d)閉環系統的誤差傳遞函數.PPT

(d)閉環系統的誤差傳遞函數3. 控制系統的方框圖模型 若已知控制系統的方框圖,使用MATLAB函數可實現方框圖轉換。 a).串聯 如圖所示G1(s)和G2(s)相串聯,在MATLAB中可用串聯函數series( )來求G1(s)G2(s),其調用格式為 [num,den]series(num1,den1,num2,den2) 其中&#xff1a; b)并…