• JS函数大全


    indexOf 方法
    返回 String 对象内第一次出现子字符串的字符位置。

    strObj.indexOf(subString[, startIndex])

    参数
    strObj

    必选项。String 对象或文字。

    subString

    必选项。要在 String 对象中查找的子字符串。

    starIndex

    可选项。该整数值指出在 String 对象内开始查找的索引。如果省略,则从字符串的开始处查找。

    说明
    indexOf 方法返回一个整数值,指出 String 对象内子字符串的开始位置。如果没有找到子字符串,则返回 -1。

    如果 startindex 是负数,则 startindex 被当作零。如果它比最大的字符位置索引还大,则它被当作最大的可能索引。

    从左向右执行查找。否则,该方法与 lastIndexOf 相同。

    示例
    下面的示例说明了 indexOf 方法的用法。

    function IndexDemo(str2){
    var str1 = "BABEBIBOBUBABEBIBOBU"
    var s = str1.indexOf(str2);
    return(s);
    }

    setInterval 定时触发

    用法:timerID = setInterval(codeStr, milliSeconds);

    timerID 是 setInterval 的返回值,返回定时器的 ID,当然也可以不要返回值。

    codeStr 是要执行的代码。

    milliSeconds 是触发的间隔时间,单位为毫秒。

    示例:setInterval("alert('您好!');", 2000);每 2 秒钟弹出一个对话框。

    clearInterval 清除定时器

    用法:clearInterval(timerID)

    timerID 就是 setInterval 的返回值。

    JavaScript有许多小窍门来使编程更加容易。
    其中之一就是eval()函数,这个函数可以把一个字符串当作一个JavaScript表达式一样去执行它。
    举个小例子:


    var the_unevaled_answer = "2 + 3";
    var the_evaled_answer = eval("2 + 3");
    alert("the un-evaled answer is " + the_unevaled_answer + " and the evaled answer is " + the_evaled_answer);


    如果你运行这段eval程序, 你将会看到在JavaScript里字符串"2 + 3"实际上被执行了。
    所以当你把the_evaled_answer的值设成 eval("2 + 3")时, JavaScript将会明白并把2和3的和返回给the_evaled_answer。
    这个看起来似乎有点傻,其实可以做出很有趣的事。比如使用eval你可以根据用户的输入直接创建函数。
    这可以使程序根据时间或用户输入的不同而使程序本身发生变化,通过举一反三,你可以获得惊人的效果。
    在实际中,eval很少被用到,但也许你见过有人使用eval来获取难以索引的对象。

    文档对象模型(DOM)的问题之一是:有时你要获取你要求的对象简直就是痛苦。
    例如,这里有一个函数询问用户要变换哪个图象:变换哪个图象你可以用下面这个函数:

    function swapOne()
    {
    var the_image = prompt("change parrot or cheese","");
    var the_image_object;

    if (the_image == "parrot")
    {
    the_image_object = window.document.parrot;
    }
    else
    {
    the_image_object = window.document.cheese;
    }

    the_image_object.src = "ant.gif";
    }


    连同这些image标记:

    [img src="http://a.com/a.gif" name="parrot"]
    [img src="http://b.com/b.gif" name="cheese"]
    [code]
    请注意象这样的几行语句:
    [code]
    the_image_object = window.document.parrot;


    它把一个图象对象敷给了一个变量。虽然看起来有点儿奇怪,它在语法上却毫无问题。
    但当你有100个而不是两个图象时怎么办?你只好写上一大堆的 if-then-else语句,要是能象这样就好了:

    function swapTwo()
    {
    var the_image = prompt("change parrot or cheese","");
    window.document.the_image.src = "ant.gif";
    }


    不幸的是, JavaScript将会寻找名字叫 the_image而不是你所希望的"cheese"或者"parrot"的图象,
    于是你得到了错误信息:”没听说过一个名为the_image的对象”。

    还好,eval能够帮你得到你想要的对象。

    function simpleSwap()
    {
    var the_image = prompt("change parrot or cheese","");
    var the_image_name = "window.document." + the_image;
    var the_image_object = eval(the_image_name);
    the_image_object.src = "ant.gif";
    }


    如果用户在提示框里填入"parrot",在第二行里创建了一个字符串即window.document.parrot. 然后包含了eval的第三
    行意思是: "给我对象window.document.parrot" - 也就是你要的那个图象对象。一旦你获取了这个图象对象,你可以把
    它的src属性设为ant.gif. 有点害怕?用不着。其实这相当有用,人们也经常使用它。
    我们常常在Javascript中间到Eval这个函数,
    有些人觉得这个函数很奇怪,可以把一些字符串变的功能很强大
    在我们需要将普通的字符串转变成具体的对象的时候,就会用到这个函数

    eval 函数对作为数字表达式的一个字符串进行求值,其语法为:

    eval(expr)

    此处 expr 是一个被求值的字符串参数。如果该字符串是一个表达式,eval 求该表达式的值;如果该参数代表一个或多个 JavaScript 语句,那么 eval 执行这些语句。eval 函数可以用来把一个日期从一种格式(总是字符串)转换为数值表达式或数字。


    ==============================
    Eval 函数
    功能:先解释Javascript代码,然后在执行它
    用法:Eval(codeString)
    codeString是包含有Javascript语句的字符串,在eval之后使用Javascript引擎编译。

    注释:

    例子:eval(id + "_icon.src="http://c.com/collapse_up.gif'");
    id是之前设定的参数,而在双引号中的字符串则是需要编译的

    引用:
    --------------------------------------------------------------------------------

    function tophide(id) //id indicates menu
    {
    if (top.topframeset.rows == "31,*")
    {
    top.topframeset.rows = "86,*";
    eval(id + "_icon.src="http://c.com/collapse_up.gif'");
    eval(id + "_icon.alt='Collapse The Head'");
    head.style.display = "block"
    }
    else
    {
    top.topframeset.rows = "31,*";
    eval(id + "_icon.src="http://c.com/collapse_down.gif'");
    eval(id + "_icon.alt='Expand The Head'");
    head.style.display = "none"
    }
    }

    <SCRIPT LANGUAGE="javascript"> 
    <!-- 
    window.open ('page.html', 'newwindow', 'height=100, width=400, top=0, left=0, toolbar=no, menubar=no, scrollbars=no, resizable=no,location=no, status=no') 
    //写成一行 
    --> 
    </SCRIPT> 


    参数解释:
      <SCRIPT LANGUAGE="javascript"> js脚本开始;
    window.open 弹出新窗口的命令;
    page.html 弹出窗口的文件名;
    newwindow 弹出窗口的名字(不是文件名),非必须,可用空''代替;
    height=100 窗口高度;
    width=400 窗口宽度;
    top=0 窗口距离屏幕上方的象素值;
    left=0 窗口距离屏幕左侧的象素值;
    toolbar=no 是否显示工具栏,yes为显示;
    menubar,scrollbars 表示菜单栏和滚动栏。
    resizable=no 是否允许改变窗口大小,yes为允许;
    location=no 是否显示地址栏,yes为允许;
    status=no 是否显示状态栏内的信息(通常是文件已经打开),yes为允许;
    </SCRIPT> js脚本结束


    //====================手机评测转换DIV=====================
    function changediv(divcount,olddivall,newdiv,newdivclass,olddivclass,listdiv,listdivall){
       for(var p=0;p<divcount;p++){
       document.getElementById(olddivall+p).className=newdivclass;
       document.getElementById(listdivall+p).style.display='none';
      }
      document.getElementById(newdiv).className=olddivclass;
      document.getElementById(listdiv).style.display='block';
    }

    //手机新闻排行转换DIV
    function changediv_ph(listdiv,disdiv){
      document.getElementById(disdiv).style.display='none';
      document.getElementById(listdiv).style.display='block';
    }

    //常用到的js方法
    //author: 钟国勇
    //date  : 2006-11-04
     
    //去掉空格  没写
    //用法:  var str = " abc ";
    //       str = str.trim()
    String.prototype.trim = function()
    {
      
        return this;
    }
    //过滤危险字符
    function filtrate(content)
    {
    //    //过滤所有事件和脚本
    //    str = str.replace(/<script(.|\n)*\/script>\s*/ig, "");
    //    str = str.replace( /<[^>]+/ig, function($0){return $0.replace(/\s*on\w+=[^ ]+/ig, "")});
    //  
    //    //清楚所有html标签
    //    str = str.replace((?<Style><style[\s\S]+?/style>)|(?<Script><script[\s\S]*?/script>)|(?<Explein><\!\-\-[\s\S]+?\-\->)|(?<Html></?\s*[^> ]+(\s*[^=>]+?=['"]?[^"']+?['"]?)*[^>]*>)|(?<Other>( )|(")|(&)|(·))|(?<Space>\s+),"");
     
      
        //过滤我用来分隔信息的特殊字符
        content = content.replace("|","|");
        return content;  
    }
    //根据对象ID获取对象
    function getObject(objId)
    {
        if(typeof(objId)=='object') return objId;
        return document.getElementById(objId);
    }
    //使图片根据设定的高宽自适应大小
    //用法: <img src="zzz.gif" style="zoom:0.1;" onload="SetSize(this,100,100)" alt="xxx" />
    function SetSize(obj, width, height)
    {
        myImage = new Image();
        myImage.src = obj.src;
        if (myImage.width>0 && myImage.height>0)
        {
            var rate = 1;
            if (myImage.width>width || myImage.height>height)
            {
                if (width/myImage.width<height/myImage.height)
                {
                    rate = width/myImage.width;
                }
                else
                {
                    rate = height/myImage.height;
                }
            }
            if (window.navigator.appName == "Microsoft Internet Explorer")
            {
              obj.style.zoom = rate;
            }
            else
            {
              obj.width = myImage.width*rate;
              obj.height = myImage.height*rate;
            }
        }
    }
    //清空指定对象的值
    function clear(objId) 
    {
        document.getElementById(objId).value = "";
    }
    //指示指定对象是否可用,true为禁用,false可用
    function changeDisable(objId,isDisable)
    {
        if(isDisable)
        {
            getObject(objId).disabled = "disabled";
        }
        else
        {
            getObject(objId).disabled = "";
        }
    }
    //指示指定对象是否显示,true为显示,false隐藏
    function changeDisplay(objId,isDisplay)
    {
        if(isDisplay)
        {
            getObject(objId).style.display = "";
        }
        else
        {
            getObject(objId).style.display = "none";
        }
    }
    //显示提示信息
    //param:
    //  objId 要显示信息的对象ID,建议使用div,然后在该div上套用自己的样式.  msg:提示信息.  time:多久后自动隐藏,0为不隐藏.
    function ShowMsg(objId,msg,time)
    {
        var obj = getObject(objId);
            obj.innerHTML = msg;
            obj.style.display = "";
        if(time != 0) window.setTimeout("HidMsg("+objId+")",time);
    }
    //隐藏提示信息
    function HidMsg(objId)
    {
        if(typeof(objId)=='object')
        {
            objId.style.display = "none";
        }
        else
        {
            var obj = getObject(objId);   
                obj.style.display = "none";
        }
    }
    //
    //一个表单输入值检测类
    //author:钟国勇
    //date  :2006-11-06
    //e.g.
    //  先定义样式
    //  <script>
    //      Checker.ErrStyle = 'Err';
    //      Checker.RightStyle = 'Right';
    //  </script>
    //  <input id="realName" onblur="Checker.Check(this)" onfocus="Checker.Check(this)" check="Chinese" />
    //
    function Checker(){
        this.Version = "v 1.0";
        this.Author = "钟国勇";
        this.LastModify = "2006-11-06";
    }
        //必填项
        Checker.Require = function chkRequire(v){
            return regex(/.+/,v);
        }
        //Email地址
        Checker.Email = function chkEmail(v){
            return regex(/^\w+([-+.]\w+)*@\w+([-.]\\w+)*\.\w+([-.]\w+)*$/);
        }
        //电话
        Checker.Telphone = function chkTelphone(v){
            return regex(/^((\(\d{3}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?[1-9]\d{6,7}$/,v);
        }
        //手机
        Checker.Mobile = function chkMobile(v){
            return regex(/^((\(0?13\d{1}\))|(0?13\d{1}))(\-?)(\d{8})$/,v);     
        }
        //Url格式
        Checker.Url = function chkUrl(v){
            return regex(/^http:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/,v);
        }
        //身份证
        Checker.IDCard = function chkIDCard(v){
            return regex(/^\d{15}(\d{2}[A-Za-z0-9])?$/,v);
        }
        //货币
        Checker.Currency = function chkCurrency(v){
            return regex(/^\d+(\.\d+)?$/,v);
        }
        //邮政编码
        Checker.Zip = function chkZip(v){
            return regex(/^[1-9]\d{5}$/,v);
        }
        //QQ
        Checker.QQ = function chkQQ(v){
            return regex(/^[1-9]\d{4,8}$/,v);
        }    
        //是否为中文
        Checker.Chinese =function chkChinese(v){
            return regex(/^[\u0391-\uFFE5]+$/,v);
        }
        //是否为英文
        Checker.English = function chkEnglish(v){
            return regex(/^[A-Za-z]+$/,v);
        }
        //是否为数字
        Checker.Number = function chkNumber(v){
            return regex(/^\d+$/,v);
        }
        //是否为整数
        Checker.Integer = function chkInteger(v){
            return regex(/^[-\+]?\d+$/,v);
        }
        //是否为实数
        Checker.Double = function chkDouble(v){
            return regex(/^[-\+]?\d+(\.\d+)?$/,v);
        }
        //是否为不安全密码,不安全为true
        Checker.UnSafe = function chkUnSafe(v){
            return regex(/^(([A-Z]*|[a-z]*|\d*|[-_\~!@#\$%\^&\*\.\(\)\[\]\{\}<>\?\\\/\'\"]*)|.{0,5})$|\s/,v);
        }
        //日期
        //  op:检测的日期值,
        //  formatString:检测的日期格式 (ymd:年-月-日,dmy:日-月-年)
        Checker.Date = function(op, formatString){
      formatString = formatString || "ymd";
      var m, year, month, day;
      switch(formatString){
       case "ymd" :
        m = op.match(new RegExp("^\\s*((http://www.cnblogs.com/itecho/admin/file://d%7b4%7d)%7c(//d%7B2%7D))([-./])(//d%7B1,2%7D)//4(//d%7B1,2%7D)//s*$"));
        if(m == null ) return false;
        day = m[6];
        month = m[5]--;
        year =  (m[2].length == 4) ? m[2] : GetFullYear(parseInt(m[3], 10));
        break;
       case "dmy" :
        m = op.match(new RegExp("^\\s*(http://www.cnblogs.com/itecho/admin/file://d%7b1,2%7d)([-./])(//d%7B1,2%7D)//2((//d%7B4%7D)%7C(//d%7B2%7D))//s*$"));
        if(m == null ) return false;
        day = m[1];
        month = m[3]--;
        year = (m[5].length == 4) ? m[5] : GetFullYear(parseInt(m[6], 10));
        break;
       default :
        break;
      }
      var date = new Date(year, month, day);
            return (typeof(date) == "object" && year == date.getFullYear() && month == date.getMonth() && day == date.getDate());
      function GetFullYear(y){return ((y<30 ? "20" : "19") + y)|0;}
     }
     //是否超出给定的范围
     //  v:值
     //  min:最小长度
     //  max:最大长度
     //
     Checker.Limit = function chkLimit(v,min,max){
         var len = v.length;
      min = min || 0;
      max = max || Number.MAX_VALUE;
      return min <= len && len <= max;
     }
     //设定用来显示提示信息的对象ID
     Checker.ObjMsg = "";
     //是否提示信息
     //  isDisplay:是否要显示,true为显示
     //  Msg:提示信息
     //  time:多少毫秒后隐藏,0为永久不隐藏
     Checker.Msg = function showMsg(isDisplay,Msg,time){
         if(isDisplay){
             ShowMsg(Checker.ObjMsg,Msg,time);
         }
         return isDisplay;
     }
     //出现错误的提示样式
     Checker.ErrStyle = "";
     //正确时的样式
     Checker.RightStyle = "";
     //是否改变对象的样式
     Checker.ChangeStyle = function changeStyle(objId,isChange){
         var obj = getObject(objId);
         if(isChange){
             obj.className = Checker.ErrStyle;
         }else{
             obj.className = Checker.RightStyle;
         }   
         return isChange;
     }
     //放在HTML控件里的检测方法
        Checker.Check = function check(obj){
            var checkType = obj.getAttribute("check");
            if(typeof(checkType)=='object' || typeof(eval(Checker[checkType]))=='undefined'){
                return;
            }      
            var checked = eval(Checker[checkType](obj.value));
            if(!checked){
                var msg = obj.getAttribute("message");
                var showobj = obj.getAttribute("showobj");
                if(msg != null && showobj != null){
                    ShowMsg(getObject(showobj),msg,0);
                }
            }
            return Checker.ChangeStyle(obj,!checked);
        }
        //清除样式
        Checker.ClearStyle = function clearStyle(obj){
            getObject(obj).className = "";
            var msg = obj.getAttribute("message");
            var showobj = obj.getAttribute("showobj");
            if(msg != null && showobj != null){
                getObject(showobj).innerHTML = "";
            }
        }
      
    //根据正则表达式检测值
    function regex(regStr,v){
        var reg = regStr;
        return reg.test(v);
    }
    文章引用自:

  • 相关阅读:
    PHP里文件的查找方式及写法
    上传文件
    用ajax对数据进行查看人员信息
    ajax实现分页
    jquery做个日期选择适用于手机端
    PHP用ajia代码写三级联动下拉
    JSON数据的定义
    jquery做一些小的特效
    对jquery操作复选框
    使用 LUT 模拟光照
  • 原文地址:https://www.cnblogs.com/itecho/p/1307118.html
Copyright © 2020-2023  润新知