js 常用方法
(1)startWith
- var startsWith = function (str, regex) {
- if (regex == undefined || str == undefined || (!str) || (!regex)) {
- return false;
- }
- return str.indexOf(regex) == 0;
- };
测试:
- console.log(startsWith('123abc',''));
(2)trim
- var trim = function (str) {
- if (typeof str === "object") {
- return str;
- }
- if (str == null || str == "" || str == undefined) {
- return str;
- }
- if (typeof str === "number") {
- return str;
- }
- return str.replace(/(^\s*)|(\s*$)/g, "");
- };
应用:
- var cssColor2Hex = function (cssColor) {
- var stringObj = cssColor.replace(/RGB[\s]*\(([\w,\s]+)\)[\s]*/i, "$1");
-
- var arr = stringObj.split(',');
- var r = trim(arr[0]);
- var g = trim(arr[1]);
- var b = trim(arr[2]);
- var rHex = to2Hex(r);
- var gHex = to2Hex(g);
- var bHex = to2Hex(b);
- return (rHex + gHex + bHex);
- };
(3)是否包含特殊字符
-
-
-
-
-
- var containsSpecialCharacter = function (str) {
- var reg = /[@#$?*!?]/g;
- return reg.test(str);
- };
应用:
- if (containsSpecialCharacter(orgFullName_val)) {
- setErrerMessageAndFocus($error_create_org, $orgFullName, '不能包含非法字符');
- return;
- }
(4)动态加载js脚本文件
-
-
-
-
-
- function loadJs(url, callback) {
- var done = false;
- var script = document.createElement('script');
- script.type = 'text/Javascript';
- script.language = 'Javascript';
- script.charset = "utf-8";
- script.src = url;
-
- script.onload = script.onreadystatechange = function () {
- if (!done && (!script.readyState || script.readyState == 'loaded' || script.readyState == 'complete')) {
- done = true;
- script.onload = script.onreadystatechange = null;
- if (callback) {
- callback.call(script);
- }
- }
- };
- document.getElementsByTagName("head")[0].appendChild(script);
- };
应用:
- readyCallBack=function(){
- $(document).ready(function(){
-
- clearError=function(){
- $(".errorMessage").hide(1000);
- };
- $(document).bind("keypress",clearError);
- var loginStatus = document.getElementById("loginStatus");
- if(loginStatus.value&#61;&#61;<%&#61;LoginConstants.ACCOUNT_LOGINED%>){
- jAlert("",null,function(){window.location.href&#61;&#39;&#39;;});
- }
- });
- loadJs(&#39;&#39;);
- loadJs(&#39;&#39;);
- };
- loadJs(&#39;&#39;,readyCallBack);
参考:
http://hw1287789687.iteye.com/blog/2196104
http://hw1287789687.iteye.com/blog/2196716
http://hw1287789687.iteye.com/blog/2196836