Home > Web Front-end > JS Tutorial > Summary of common javascript operations_javascript skills

Summary of common javascript operations_javascript skills

WBOY
Release: 2016-05-16 16:37:41
Original
1167 people have browsed it

本文整理汇总了javascript常见的各类操作,包括字符串、时间、表单、正则验证等等。有着极高的参考价值。分享给大家供大家参考之用。具体方法如下:

/***** BasePage.js 公共的 脚本文件 部分方法需引用jquery库 *****/
 
//#region 日期操作
 
//字符串转化为时间。
function stringtoTime(date1) {
  var dt = new Date(Date.parse(date1.replace(/-/g, "/")));
  return dt;
}
 
// 使用 var date1 = "2013-06-08 15:23:31"或"2013/6/8 9:9:00"格式;
//-------------------------------------------------------------
// 日期格式化
Date.prototype.format = function (format) {
  var o = {
    "M+": this.getMonth() + 1, //month 
    "d+": this.getDate(), //day 
    "h+": this.getHours(), //hour 
    "m+": this.getMinutes(), //minute 
    "s+": this.getSeconds(), //second 
    "q+": Math.floor((this.getMonth() + 3) / 3), //quarter 
    "S": this.getMilliseconds() //millisecond 
  }
 
  if (/(y+)/.test(format)) {
    format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  }
 
  for (var k in o) {
    if (new RegExp("(" + k + ")").test(format)) {
      format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
    }
  }
  return format;
}
 
////使用方法 
 
//alert(newdate.format("yyyy-MM-dd"));
//alert(newdate.format("MM/dd/yyyy"));
//var nowStr = now.format("yyyy-MM-dd hh:mm:ss"); Math.round(Math.random() * 10000)
////使用方法2: 
//var testDate = new Date();
//var testStr = testDate.format("yyyy年MM月dd日hh小时mm分ss秒");
////示例: 
//alert(testDate.format("yyyy年MM月dd日"));
//-------------------------------------------------------------
//设置周期内的日期(数组)
function SetFlag(start, end) {
  var cdate = Array();
  cdate = start.split("-");
  var cd = cdate[1] + "/" + cdate[2] + "/" + cdate[0];
  var dayNum = DateDiff(end, start);
  for (var i = 0; i <= dayNum; i++) {
    flag.push(AddDays(cd, i));
  }
} //end fun
 
//日期加上天数后的新日期.
function AddDays(date, days) {
  var nd = new Date(date);
  nd = nd.valueOf();
  nd = nd + days * 24 * 60 * 60 * 1000;
  nd = new Date(nd);
  //alert(nd.getFullYear() + "年" + (nd.getMonth() + 1) + "月" + nd.getDate() + "日");
  var y = nd.getFullYear();
  var m = nd.getMonth() + 1;
  var d = nd.getDate();
  if (m <= 9) m = "0" + m;
  if (d <= 9) d = "0" + d;
  var cdate = y + "-" + m + "-" + d;
  return cdate;
}

//两个日期的差值(d1 - d2).
function DateDiff(d1, d2) {
  var day = 24 * 60 * 60 * 1000;
  try {
    var dateArr = d1.split("-");
    var checkDate = new Date();
    checkDate.setFullYear(dateArr[0], dateArr[1] - 1, dateArr[2]);
    var checkTime = checkDate.getTime();
 
    var dateArr2 = d2.split("-");
    var checkDate2 = new Date();
    checkDate2.setFullYear(dateArr2[0], dateArr2[1] - 1, dateArr2[2]);
    var checkTime2 = checkDate2.getTime();
 
    var cha = (checkTime - checkTime2) / day;
    return cha;
  } catch (e) {
    return false;
  }
} //end fun
 
//#endregion
 
//#region URL操作
 
/*
* 根据QueryString参数名称获取值
*/
function getQueryStringByName(name) {
  var result = location.search.match(new RegExp("[\&#63;\&]" + name + "=([^\&]+)", "i"));
  if (result == null || result.length < 1)
    return "";
 
  return result[1];
}
 
function GetQueryString(name) {
  // 如果链接没有参数,或者链接中不存在我们要获取的参数,直接返回空
  if (location.href.indexOf("&#63;") == -1 || location.href.indexOf(name + '=') == -1) {
    return '';
  }
 
  // 获取链接中参数部分
  var queryString = location.href.substring(location.href.indexOf("&#63;") + 1);
 
  // 分离参数对 &#63;key=value&key2=value2
  var parameters = queryString.split("&");
 
  var pos, paraName, paraValue;
  for (var i = 0; i < parameters.length; i++) {
    // 获取等号位置
    pos = parameters[i].indexOf('=');
    if (pos == -1) {
      continue;
    }
    // 获取name 和 value
    paraName = parameters[i].substring(0, pos);
    paraValue = parameters[i].substring(pos + 1);
    // 如果查询的name等于当前name,就返回当前值,同时,将链接中的+号还原成空格
    if (paraName == name) {
      return unescape(paraValue.replace(/\+/g, " "));
    }
  }
  return '';
}
 
/*
* 获取当前地址的小写文件名
*/
function getCurrentUrlName() {
  var url = window.location.href;
  url = url.toLocaleLowerCase();
  if (url == undefined || url == "")
    return "";
  var item = url.toString().split("/");
  var name = item[item.length - 1];
  name = name.toString().split(".");
  if (name.length == 2)
    return name[0].toString();
  else return "";
}
 
//#endregion
 
//#region 字符串操作
 
/*
* 截取指定长度字符串
* 参数:
*   strString: 需要截取的字符串
*   strStart: 开始的索引
*   intLen:  截取的长度
*/
function getCustomLengtStr(strString, strStart, intLen) {
  if (strString != undefined && strString != "" && strString != null) {
    var CLen = strString.toString().length;
    if ((strStart + intLen) <= CLen - 1) {
      if (strStart < 0) strStart = 0;
 
      return strString.toString().substr(strStart, Number(intLen));
    } else {
      //长度越界,返回原始数据
      return strString;
    }
  } else return "";
}
 
/*
* 截取指定指定区间的字符串
* 参数:
*   strString: 需要截取的字符串
*   intStart: 开始的索引
*   intEnd:  结束的索引
*/
function getCustomLengtStr(strString, intStart, intEnd) {
  if (strString != undefined && strString != "" && strString != null) {
    var Clen = strString.toString().length - 1;
    if (Number(intEnd) <= Clen) {
      if (intStart < 0) intStart = 0;
      else if (intStart > Clen) intStart = Clen;
 
      return strString.toString().substring(intStart, intEnd);
    } else {
      //长度越界,返回原始数据
      return strString;
    }
  } else return "";
}
 
//#endregion
 
//#region 设为首页,添加收藏
 
//设为首页
function SetHome() {
  if (document.all) {
    document.body.style.behavior = "url(#default#homepage)";
    var url = window.location.href;
    document.body.setHomePage(url);
  } else {
    alert("设为首页失败,请手动设置!");
  }
}
 
//添加到收藏
function AddCollect() {
  var url = window.location.href;
  try {
    window.external.addFavorite(url, "美源金业");
  }
  catch (e) {
    try {
      window.sidebar.addPanel("美源金业", url, "");
    }
    catch (e) {
      alert("加入收藏失败,请使用Ctrl+D进行添加");
    }
  }
}
 
//#endregion 
 
//#region 全选/全不选
 
//CheckSelectAll(true);
 
function CheckSelectAll(check) {
  $("input[type='checkbox']").attr("checked", check)
}
 
//#endregion
 
//#region 验证码倒计时
 
//CountDown("#btnGetCode",60);
 
function CountDown(item, times) {//要操作的元素,时间(s)
  var timer = setInterval(function () {
    var btnValidate = $(item);
    if (times > 0) {
      btnValidate.attr("disabled", "false").css("opacity", "0.5").val("重新获取(" + times + ")");
      times--;
    } else {
      btnValidate.removeAttr("disabled").css("opacity", "1").val("获取验证码");
      clearInterval(timer);
    }
  }, 1000);
}
 
//#endregion
 
//#region 清除文本框默认值
 
//ClearEmpty("#txtName");
 
function ClearEmpty(obj) {//要操作的元素
  $(obj).focus(function () {
    if ($(this).val() == this.defaultValue) {
      $(this).val("");
    }
  }).blur(function () {
    if ($(this).val() == "") {
      $(this).val(this.defaultValue);
    }
  });
}
 
//#endregion
 
//#region 刷新页面
 
function Refresh() {
  window.parent.location.reload();
}
 
//#endregion
 
//#region 表单验证
 
//#region 检查是否为中文
 
// var item = checkChinese("中文");
 
function checkChinese(obj) {
  var reg = /[^\u4e00-\u9fa5]/;
  return !reg.test(obj);
}
 
//#endregion
 
//#region 检查是否为数字
 
// var item = checkNum("123");
 
function checkNum(obj) {
  var reg = /^\d+$/;
  return reg.test(obj);
}
 
//#endregion
 
//#region 检查是否为字母
 
// var item = checkLetter("abc");
 
function checkLetter(obj) {
  var reg = /^[a-zA-Z]+$/;
  return reg.test(obj);
}
 
//#endregion
 
//#region 检查是否为字母或数字
 
// var item = checkLetterNum("abc123");
 
function checkLetterNum(obj) {
  var reg = /^[a-zA-Z0-9]+$/;
  return reg.test(obj);
}
 
//#endregion
 
//#region 检查是否为字母或中文
 
// var item = checkLetterNum("abc123");
 
function checkLetterChina(obj) {
  var reg = /^[A-Za-z\u4E00-\u9FA5]+$/;
  return reg.test(obj);
}
 
//#endregion
 
//#region 检查是否为字母或中文或数字
 
// var item = checkLetterNum("abc123");
 
function checkLetterChinaNum(obj) {
  var reg = /^[a-zA-Z0-9\u4E00-\u9FA5]+$/;
  return reg.test(obj);
}
 
//#endregion
 
//#region 检查手机号码格式
 
// var item = checkMobile("13888888888")
 
function checkMobile(obj) {
  var reg = /^[1][3458][0-9]{9}$/;
  return reg.test(obj);
}
 
//#endregion
 
//#region 检查邮箱格式
 
// var item = checkEmail("abc@123.com")
 
function checkEmail(obj) {
  var reg = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
  return reg.test(obj);
}
 
//#endregion
 
//#region 检查身份证格式
 
// var item = checkIDCard("555555555555555555")
 
function checkIDCard(obj) {
  var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
  return reg.test(obj);
}
 
//#endregion
 
//随机数
function GetRandomNum(Min, Max) {
  var Range = Max - Min;
  var Rand = Math.random();
  return (Min + Math.round(Rand * Range));
} 
 
//#endregion

Copy after login

相信本文所述对大家运用javascript进行WEB程序设计有不错的借鉴价值。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template