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");
- //console.log(stringObj);
- 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)是否包含特殊字符
- /***
- * 判断是否包含特殊字符
- * @param str
- * @returns {boolean}
- */
- var containsSpecialCharacter = function (str) {
- var reg = /[@#$?*!?]/g;
- return reg.test(str);
- };
应用:
- if (containsSpecialCharacter(orgFullName_val)) {
- setErrerMessageAndFocus($error_create_org, $orgFullName, '不能包含非法字符');
- return;
- }
(4)动态加载js脚本文件
- /***
- * 动态加载javascript 脚本文件
- * @param url
- * @param callback
- */
- 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.setAttribute('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==<%=LoginConstants.ACCOUNT_LOGINED%>){
- jAlert("<s:text name='login.user.sameLogined' />",null,function(){window.location.href='<s:url action="home"/>';});
- }
- });
- loadJs('<s:url value="/js/jquery.bgiframe.js" />');
- loadJs('<s:url value="/js/alert/jquery.alerts.js" />');
- };
- loadJs('<s:url value="/js/jquery-1.9.0.min.js" />',readyCallBack);
参考:
http://hw1287789687.iteye.com/blog/2196104
http://hw1287789687.iteye.com/blog/2196716
http://hw1287789687.iteye.com/blog/2196836
时间: 2024-12-21 22:21:02