XiYO

现实不同情弱者,命运不相信眼泪。
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

js常用方法

Posted on 2011-01-27 09:54  XiYO  阅读(624)  评论(0编辑  收藏  举报

//常用方法

function StrCode(str)
{
 if(encodeURIComponent)
   return encodeURIComponent(str);
 if(escape)
   return escape(str);
}

function UnStrCode(str)
{
 if(decodeURIComponent )
   return decodeURIComponent (str);
 if(unescape)
   return unescape(str);
}

function IsNumber(num)
{
 var m = num.match(/^\d*$/);
 if (m==null)
 {
  return false;
 }
 else
 {
  return true;
 }
}

function isDecimal( str ){  

if(isInteger(str)) return true;

var re = /^[-]{0,1}(\d+)[\.]+(\d+)$/;

if (re.test(str)) {

if(RegExp.$1==0&&RegExp.$2==0) return false;

return true;

} else {

return false;

}

}

function isInteger( str ){ 

var regu = /^[-]{0,1}[0-9]{1,}$/;

return regu.test(str);

}

function Trim(s)
{
 var m = s.match(/^\s*(\S+(\s+\S+)*)\s*$/);
 return (m == null)?"":m[1];
}
String.prototype.trim=function(){return this.replace(/(^\s*)|(\s*$)/g, "");}
//转换常用转义字符
function HtmlEncode(text)
{
 var re = {'<':'&lt;','>':'&gt;','&':'&amp;','"':'&quot;'};
 for (i in re)
  text = text.replace(new RegExp(i,'g'), re[i]); 
 return text;
}

function HtmlDecode(text)
{
 var re = {'&lt;':'<','&gt;':'>','&amp;':'&','&quot;':'"'};
 for (i in re)
  text = text.replace(new RegExp(i,'g'), re[i]);
 return text;
}

//判断当前页控件ID是否存在
function gid(id)
{
 return document.getElementById(id)?document.getElementById(id):null;
}

function gna(id)
{
 return document.getElementsByName?document.getElementsByName(id):null;
}

function gname(name)
{
 return document.getElementsByTagName?document.getElementsByTagName(name):new Array()
}

    
 //判断浏览器
function Browser()
{
 var ua, s, i;
 this.isIE = false;
 this.isNS = false;
 this.isOP = false;
 this.isSF = false;
 ua = navigator.userAgent.toLowerCase();
 
 s = "opera";
 if ((i = ua.indexOf(s)) >= 0)
 {
  this.isOP = true;return;
 }
 
 s = "msie";
 if ((i = ua.indexOf(s)) >= 0)
 {
  this.isIE = true;
  return;
 }
 
 s = "netscape6/";
 if ((i = ua.indexOf(s)) >= 0)
 {
  this.isNS = true;return;
 }
 
 s = "gecko";
 if ((i = ua.indexOf(s)) >= 0)
 {
  this.isNS = true;
  return;
 }
 
 s = "safari";
 if ((i = ua.indexOf(s)) >= 0)
 {
  this.isSF = true;
  return;
 }
}

 
//计算字节数(byte length)
String.prototype.lenB = function()
{
 return this.replace(/[^\x00-\xff]/g,"**").length; 
}

 

function LockContentBox(id)
{
 if ( gid(id) )
  gid(id).disabled = true;
}

function UnLockContentBox(id)
{
 if ( gid(id) )
  gid(id).disabled = false;
}

 

//获取网站虚拟目录
var _RootPath = "";
function getRootPath(){
 if(_RootPath.length == 0){
  var strFullPath=window.document.location.href;
  var strPath=window.document.location.pathname;
  var pos=strFullPath.indexOf(strPath);
  var prePath=strFullPath.substring(0,pos);
  var postPath=strPath.substring(0,strPath.substr(1).indexOf('/')+1);
  _RootPath = prePath+postPath;
 }
 return _RootPath;
}