常用js函数

/*******************************
**功能:实现在一段字符串中查找某个字符或者字符串出现的位置
**作者:lin.su
**时间:2011年10月17日23:02:02
**参数str:需要的目标字符串
**参数searchfor:在目标字符串中匹配的字符串或者字符
**参数count:需要在目标字符串出现次数
**调用示例:Tool.GetPositionByStr("lin.su",'s',1) return 4
*******************************/
GetPositionByStr:function(str,searchfor ,count){
var re = new RegExp(searchfor,"g");

while(count--){
re.test(str);
}

var pos = re.lastIndex-searchfor.length;
if(pos < 0)
return "not index!";
else
return pos;
}

/*******************************
**功能:实现load事件的加载
**作者:lin.su
**时间:2011年10月24日22:48:54
**参数func:函数名称
**调用示例:Tool.AddLoadEvent(func)
*******************************/
AddLoadEvent:function(func){
var oldonload = window.onload;//得到上一个onload事件的函数
if (typeof window.onload != 'function') {//判断类型是否为'function',注意typeof返回的是字符串
window.onload = func;
} else {
window.onload = function() {
oldonload();//调用之前覆盖的onload事件的函数---->由于我对js了解不多,这里我暂时理解为通过覆盖onload事件的函数来实现加载多个函数
func();//调用当前事件函数
}
}

}

/*******************************
**功能:按字节数截取左侧字符串
**作者:lin.su
**时间: 2011年10月26日21:46:14
**参数str:需要计算的字符串
**参数len:需要计算的字符串
**调用示例:Tool.StrSubLength("123中",2)
*******************************/
StrSubLength:function(str,len){
var count=0;
var asc;
var returnstr
for (var i=0;i<str.length;i++) {
asc = str.charCodeAt(i);
if (asc < 0) asc += 65536;
if (asc > 255) count++;
if (i + count >= len) {
returnstr = str.substr(0, i);
break;
}

}
return returnstr;
}

/*******************************
**功能:产生一个随机数当做参数发送到服务器
**作者:lin.su
**时间: 2011年10月26日22:21:40
**调用示例:Tool.LoadJsCssFile()
*******************************/
LoadJsCssFile:function(filename,filetype){
if(filetype=="js"){//判断文件类型
var fileref=document.createElement("script");//创建标签
fileref.setAttribute("type","text/javascript")//定义属性type的值为text/javascript
fileref.setAttribute("src", filename)//文件的地址
}
else if(filetype=="css"){
var fileref=document.createElement("link");
fileref.setAttribute("rel","stylesheet");
fileref.setAttribute("type","text/css");
fileref.setAttribute("href",filename);
}
if (typeof fileref!="undefined")
document.getElementsByTagName("head")[0].appendChild(fileref)
}

原文地址:https://www.cnblogs.com/linsu/p/2307955.html