首页 > 代码库 > JS/Jquery常用代码1

JS/Jquery常用代码1

1.Jquery解析Json数据:        var remark_msg=jQuery.parseJSON(result);            $.each(remark_msg,function(i,n)            {                  $("#remark_content").val(n.remark);                $("#remark_msg").html(n.name+"于"+n.rtime+"备注!");            } )     2.数据确认:        var r=confirm(‘您确认要清除所分配的医院吗?‘);                    if(r==true)                    {                        par=‘‘;                    }else                    {                        return false;                    }    3.删除空格:$.trim();    4.保留小数位数:money.toFixed(2);    5.数字验证:    if($.trim(rtime)==""||isNaN(rtime))        {            $("#remark").html("准备时间输入错误,请检查!");            $("#readytime").select();            return false;        }    6.刷新页面:location.reload();    7.JS取整:Math.ceil(pagesum/pagesize);    8.去处最后一个字符:did=did.substring(0,did.length-1);    9.JS处理PHP数组:        $("#specialty").empty();            var spe_sel;            switch(value)            {                case "1":                spe_sel=<?php echo  json_encode($specialty_sel[‘临床‘])?>;                break;                case "2":                spe_sel=<?php echo json_encode($specialty_sel[‘中医‘])?>;                break;                case "3":                spe_sel=<?php echo json_encode($specialty_sel[‘口腔‘])?>;                break;                case "4":                spe_sel=<?php echo json_encode($specialty_sel[‘公共卫生‘])?>;                break;                case "5":                spe_sel=<?php echo json_encode($specialty_sel[‘人文医学‘])?>;                break;                default:                spe_sel=<?php echo json_encode($specialty_sel[‘临床‘])?>;                break;            }            for(var item in spe_sel)            {                $("#specialty").append("<option value=http://www.mamicode.com/‘"+item+"‘>"+spe_sel[item]+"");            }    10.JS调试:        1. console.log("Hello World!");        2.        console.group("第一组信息");            console.log("第一组第一条");            console.log("第一组第二条");          console.groupEnd();          console.group("第二组信息");            console.log("第二组第一条");            console.log("第二组第二条");          console.groupEnd();        3.console.dir()可以显示一个对象所有的属性和方法。        4.onsole.dirxml()用来显示网页的某个节点(node)所包含的html/xml代码。        5.console.assert()用来判断一个表达式或变量是否为真        6.console.trace()用来追踪函数的调用轨迹。        7.console.time()和console.timeEnd(),用来显示代码的运行时间。        8.console.time()和console.timeEnd(),用来显示代码的运行时间。    11.选中与隐藏:        if($("#s_speaker").attr("checked")=="checked"&&$("#s_speaker").is(":hidden"))    12.Jquery→RadioButon取值:        $("input[name=‘speakertype‘]:checked").val();    13.正整数验证:        var reg=/^[0-9]*[1-9][0-9]*$/;        !reg.test(mtime)    14.Bootstrap model的显示与隐藏:        $("#check_modal").modal();         $("#check_modal").modal(‘hide‘);    15.Jquery Ajax提交:        $.ajax({                     type: ‘POST‘,                      url: ‘/kol/index/select_doctor_msl‘ ,                     data: "sel_key="+ search_key+"&user_id="+msl_id+"&currentpage="+currentpage,                     success:function(result)                     {                            $(‘#<?php echo $user_id?>_show‘).html(result);                     },                    dataType:"text"                });    16.字符串分割:        var answers=new Array();        answers=n.answer1.split("***");        for (i=0;i<answers.length ;i++ )         {            show+="<td>"+num[i]+".   "+answers[i]+"</td>";        }    17.name选择:    $("a[name=‘sendmail_btn‘]").click(function()        {});    18.日期比较:        //验证时间                    var starttime=$("#project_starttime").val();                    var endtime=$("#project_endtime").val();                            var arr = starttime.split("-");                    var starttime = new Date(arr[0], arr[1], arr[2]);                    var starttimes = starttime.getTime();                                    var arrs = endtime.split("-");                    var lktime = new Date(arrs[0], arrs[1], arrs[2]);                    var lktimes = lktime.getTime();                             if (starttimes > lktimes)                      {                                 alert(‘结束时间必须小于等于开始时间,请检查!‘);                                 return false;                      }    19.短日期格式字符串转日期:        var stime=$(this).attr("starttime");        var starttime = new Date(Date.parse(stime.replace(/-/g,   "/")));        var starttimes = starttime.getTime();    20.HTML插入数据库:        Htmlspecialchars();    21.数组逆向排序:        rsort();    22.jquery获取table行数:        var rows = $("#tuijian_tab tr").length;    23.jquery动态添加行,删除行:    //添加推荐内容tr    $("#add_tuijian").click(    function (){         var rows = $("#tuijian_tab tr").length;         $("#tuijian_tab").append("<tr><td>标题:</td><td><input type=‘text‘ id=‘tuijian_title"+(rows+1)+"‘ class=‘form-control‘ style=‘width:60%‘ name=‘tuijian‘/></td><td>链接:</td><td><input type=‘text‘ id=‘tuijian_link"+(rows+1)+"‘ class=‘form-control‘ style=‘width:60%‘ name=‘tuijian‘/><input type=‘button‘ class=‘btn btn-primary‘ value=http://www.mamicode.com/‘删除‘ onclick=‘deleterow(this);‘/>");        });    function deleterow(par)    {        $(par).parent().parent().remove();     }    24.jquery遍历table        $("table").find("tr").each(function(){        $(this).find("td").each(function(){        alert($(this).text());        });        });    25.jquery ui autocomplete实现:        var provins = [                    {value: "sh shanghai 上海",desc: "上海"},                    {value: "bj beijing 北京",desc: "北京"},                    {value: "tj tianjin 天津",desc: "天津"},                    {value: "cq chongqing 重庆",desc: "重庆"},                    {value: "hb hebei 河北",desc: "河北"},                    {value: "hn henan 河南",desc: "河南"},                    {value: "yn yunnan 云南",desc: "云南"},                    {value: "ln liaoning 辽宁",desc: "辽宁"},                    {value: "hlj heilongjiang 黑龙江",desc: "黑龙江"},                    {value: "hn hunan 湖南",desc: "湖南"},                    {value: "ah anhui 安徽",desc: "安徽"},                    {value: "sd shandong 山东",desc: "山东"},                    {value: "xj xinjiang 新疆维吾尔",desc: "新疆维吾尔"},                    {value: "js jiangsu 江苏",desc: "江苏"},                    {value: "zj zhejiang 浙江",desc: "浙江"},                    {value: "jx jiangxi 江西",desc: "江西"},                    {value: "hb hubei 湖北",desc: "湖北"},                    {value: "gx guangxi 广西",desc: "广西"},                    {value: "gs gansu 甘肃",desc: "甘肃"},                    {value: "sx shanxi 山西",desc: "山西"},                    {value: "nm nmg neimeng 内蒙古",desc: "内蒙古"},                    {value: "sx shanxi 陕西",desc: "陕西"},                    {value: "jl jilin 吉林",desc: "吉林"},                    {value: "fj fujian 福建",desc: "福建"},                    {value: "gz guzhou 贵州 ",desc: "贵州"},                    {value: "gd guangdong 广东",desc: "广东"},                    {value: "qh qinghai 青海",desc: "青海"},                    {value: "xz xizang 西藏",desc: "西藏"},                    {value: "sc sichuan 四川",desc: "四川"},                    {value: "nx ningxia 宁夏回族",desc: "宁夏回族"},                    {value: "hn hainan 海南",desc: "海南"},                    {value: "tw taiwan 台湾",desc: "台湾"},                    {value: "xg xianggang 香港",desc: "香港"},                    {value: "am aomen 澳门",desc: "澳门"},                ];        $("#provin_id").autocomplete({                    source: provins,                     minLength: 0,    //列表里的条目数                     focus: function( event, ui ) {                     $("#provin_id" ).val( ui.item.desc);                        return false;                      },                    select: function( event, ui ) {                    $( "#provin_id" ).val( ui.item.desc );                           return false;                      }                })                $("#provin_id").data("ui-autocomplete")._renderItem = function(ul,item) {                               return $( "<li></li>")                                   .data( "item.autocomplete", item )                                   .append( "<a>"+ item.desc + "</a>" )                                   .appendTo( ul );                         };        26.Js翻页:            window.location.href=herf;         27.JS处理url地址:        //方法:            function GetRequest()             {                 var url = location.search; //获取url中"?"符后的字串                 var theRequest = new Object();                 if (url.indexOf("?") != -1)                {                     var str = url.substr(1);                     strs = str.split("&");                     for(var i = 0; i < strs.length; i ++)                    {                         theRequest[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1]);                     }                 }             return theRequest;             }         //调用:            var Request = new Object();                 Request = GetRequest();                            if(typeof(Request[‘numpage‘])=="undefined")                {                    herf="http://tk.test_drrenew.com/question/question/question_list/4/";                    num=10;                }else                {                    herf=window.location.href;                    num=Request[‘numpage‘];                }        28.undefined判断:            if(typeof(Request[‘numpage‘])=="undefined")                {                    herf="http://tk.test_drrenew.com/question/question/question_list/4/";                    num=10;                }else                {                    herf=window.location.href;                    num=Request[‘numpage‘];                }        29.indexOf,substr            if(herf.indexOf("per_page")!=-1)                    {                        herf=herf.substr(0,herf.indexOf("per_page"))+"&per_page="+pagenum;                    }                    else                    {                        herf=herf+"&per_page="+pagenum;                    }                    30.jquery循环表格,获取id:            var ids="";                //获取当前页面的试题id                     $(‘#ques_tab tr:gt(0)‘).each(function () {                        var id = $(this).find("#ques_id").html();                                                   ids+=id+",";                    });                ids=ids.substring(0,ids.length-1);        31.分割字符串:            var source_herf=window.location.href;            var par_num=source_herf.split("/");            var herf="http://tk.drrenew.com/question/question/question_list/"+par_num[par_num.length-1]+"/";        32.获取当前日期时间:            function getNowFormatDate() {                var date = new Date();                var seperator1 = "-";                var seperator2 = ":";                var year = date.getFullYear();                var month = date.getMonth() + 1;                var strDate = date.getDate();                if (month >= 1 && month <= 9) {                    month = "0" + month;                }                if (strDate >= 0 && strDate <= 9) {                    strDate = "0" + strDate;                }                var currentdate = year + seperator1 + month + seperator1 + strDate                        + " " + date.getHours() + seperator2 + date.getMinutes()                        + seperator2 + date.getSeconds();                return currentdate;            }        33.时间比较:            //验证时间                        var starttime=$("#project_starttime").val();                        if($.trim(starttime)=="")                        {                            alert("开始时间不能为空!");                            $("#project_starttime").select();                            return false;                        }                        var endtime=$("#project_endtime").val();                                                var starttime = new Date(Date.parse(starttime.replace(/-/g,   "/")));                        var starttimes = starttime.getTime();                                            var lktime = new Date(Date.parse(endtime.replace(/-/g,   "/")));                        var lktimes = lktime.getTime();                                     if (starttimes > lktimes)                          {                            alert(‘结束时间必须大于等于开始时间,请检查!‘);                            return false;                             }        34.jquery遍历table赋值:            $(‘#starttime‘).on(‘changeDate‘, function(ev){                            var start_date=ev.date;                            $("#per_list").find("tr").each(function(index, element) {                                $(this).find("td").each(function(index, element) {                                    if(index==1)                                    {                                        $(this).text(FormatDate(start_date));                                    }                                    if(index==2)                                    {                                        $(this).text(addDate(start_date,7));                                    }                                });                            });                        });                });        35.日期格式化及日期加减:            //转换成短日期格式                function FormatDate (strTime) {                return strTime.getFullYear()+"-"+(strTime.getMonth()+1)+"-"+strTime.getDate();            }                //追加日期                 function addDate(date,days){                    var d=new Date(date);                    d.setDate(d.getDate()+days);                    var m=d.getMonth()+1;                    return d.getFullYear()+‘-‘+m+‘-‘+d.getDate();                  }         36.js处理checkbox:            $(‘input[type="checkbox"]:checked‘).each(function(index, element) {                        if(this.checked)                        {                            if(reject_reason=="Others")                                temp_reject_reason=$(‘#reject_reason_form‘).find(‘#reject_reason_textbox‘).val();                            else                                temp_reject_reason=$(this).val();                        }                        reject_reason+=temp_reject_reason+"***";                                        });                    if($.trim(reject_reason).length==0)                    {                        alert(‘请选择驳回原因!‘);                        return false;                    }                    else                    {                        reject_reason=reject_reason.substring(0,reject_reason.length-3);                    }        37.Jquery解析json数据2:            $.ajax({                                 type: ‘POST‘,                                  url: ‘/qc/index/getpass_per‘ ,                                 data: "svo_id="+ svo_id,                                 success:function(result)                                 {                                         var qc_per=1;                                        var per_msg=jQuery.parseJSON(result);                                        var start_time;                                        var end_time;                                        $.each(per_msg,function(i,n)                                        {                                            if(i=="qc_per")                                                qc_per=n;                                            if(i=="start_time")                                                start_time=n;                                            if(i=="end_time")                                                end_time=n;                                        }                                        );                                        qc_per= qc_per*100+"%";                                        $("#qclist_dialog").find("#qc_per_label").text(qc_per+"  ("+start_time+"~"+end_time+")")                                        $(‘#qclist_dialog‘).modal();                                                 },                                dataType:"text"                            });            38.JavaScript页面导航:                        window.location.href=‘/speaker/show/‘;            39.ajax提交验证:                function get_level()                {                    var speaker_id=$("#speaker_id").val();                    var return_val=true;                            $.ajax({                                     type: ‘POST‘,                                       async:false,                                      url: ‘/speaker/level_suggest‘ ,                                     data: "id="+ speaker_id,                                     success:function(result)                                     {                                            if(result==101)                                            {                                                alert("occupation不能为空!");                                                return_val=false;                                                //return false;                                            }                                            else if(result==102)                                            {                                                alert("评级信息不完整,请检查!");                                                return false;                                            }                                            else if(result==103)                                            {                                                alert("当occupation为Paramedical/ others时,级别不能为Level1,Level2!");                                                return false;                                            }                                            else if(result==104)                                            {                                                var form_sub=confirm("根据你给出的评级信息,不能确定建议级别,你确定要提交吗?");                                                if(form_sub==true)                                                {                                                    return true;                                                }                                                else                                                {                                                    return false;                                                }                                            }                                            else                                            {                                                var form_sub=confirm("根据你给出的评级信息,系统建议级别为Level "+result+",你确定要提交吗?");                                                if(form_sub==true)                                                {                                                    return true;                                                }                                                else                                                {                                                    return false;                                                }                                            }                                     },                                    dataType:"text"                                });                        return return_val;                }        40.js跳转传值:            function select_permsg()            {                var sel_key=$(‘#sel_key‘).val();                window.location.href="/qc/manager/show_report?sel_key="+sel_key;             }            PHP接受使用Get方式        41.按钮禁用启用:            禁用:$(‘#reject_reason_form‘).find("#reject_ce_button").attr("disabled",true);            启用:$(‘#reject_reason_form‘).find("#reject_ce_button").removeAttr("disabled");        42.jquery获取checkbox选中值:            var is_foreign=$("input[name=‘level[is_foreign]‘]").attr("checked");        43.设置html元素的隐藏与显示:            //隐藏            $("#id").css(‘display‘,‘none‘);             //显示            $("#id").css(‘display‘,‘block‘);             或             $("#id")[0].style.display = ‘none‘;        44.Jquery 数据提交验证:            function boost()            {                var username=$.trim($("#sbox-window").find("#username").val());                var indentity_code=$.trim($("#sbox-window").find("#indentity_code").val());                if(username=="")                {                    alert(‘请输入用户名!‘);                    return false;                }                var val_result=true;                var subdata=http://www.mamicode.com/"";                if(indentity_code=="")                     subdata="username="+username;                else                     subdata="username="+username+"&indentity_code="+indentity_code;                $.ajax({                        async:false,                        type: ‘POST‘,                        url: ‘/peculiarity/user_login/boot_indentity_code‘ ,                        data:subdata,                        success:function(result)                        {                            if(result=="0"||result=="")                            {                                alert("请填写身份证号后登陆!");                                $("#sbox-window").find("#com-form-login-indentity_code").css(‘display‘,‘block‘);                                val_result=false;                            }else if(result==2)                            {                                alert("请输入正确的身份证号!");                                val_result=false;                            }else if(result==3)                            {                                alert("该身份证已存在,请检查!");                                val_result=false;                            }else if(result==4)                            {                                alert("数据验证出现问题,请与网站管理员联系!");                                val_result=false;                            }                            else if(result==1)                            {                                val_result=true;                            }                        },                        dataType:"text"                });                return val_result;            }        45.简单数据操作:        前端:        <div id="Follow_Tag_Form" class="modal hide">            <div class="modal-header">                <button data-dismiss="modal" class="close" type="button"></button>                <h3>随访标签</h3>            </div>            <div class="modal-body">                <div id="Tags_list">                <table class="table table-striped table-bordered table-hover" id="listtable" >                    <tr>                    <th>序号</th>                    <th>项目名称</th>                    <th>操作</th>                    </tr>                    <?php                     $t=0;                    foreach($tags as $item):                    $t++;                    ?>                    <tr>                    <td><?php echo $t;?></td>                    <td><?php echo $item[‘name‘];?></td>                    <td><a onclick="del_tags(‘<?php echo $item[‘id‘];?>‘);">删除</a></td>                        </tr>                    <?php endforeach;?>                </table>                </div>                     <table class="table table-striped table-bordered table-hover" id="listtable" >                     <tr>                         <td>                            标签名称:                        </td>                        <td>                        <input type="text" id="tag_text"/>                        </td>                     </tr>                     <tr>                     <td colspan="2">                         <input type="button" id="Save_tag" class="btn blue" value=http://www.mamicode.com/"保存" onclick="add_tag();"/>"color: #000000">        后台:        //添加标签        function add_tag()        {            var tag=$.trim($("#Follow_Tag_Form").find("#tag_text").val());            if(tag=="")            {                alert("标签名称不能为空!");                return false;            }            $.ajax({                    type: ‘POST‘,                    url: ‘/follow/add_tag‘ ,                    data: "tag_name="+tag,                    success:function(result)                    {                        var tags_msg=jQuery.parseJSON(result);                        var html="<table class=‘table table-striped table-bordered table-hover‘ id=‘listtable‘>";                        html+="<tr><th>序号</th><th>项目名称</th><th>操作</th></tr>";                        var p=1;                        $.each(tags_msg,function(i,n)                        {                              html+="<tr><td>"+p+"</td><td>"+n.name+"</td><td> <a  onclick=‘del_tags("+n.id+");‘>删除</a></td></tr>";                            p++;                        } );                         html+="</table>";                        $("#Follow_Tag_Form").find("#Tags_list").html(html);                        $("#Follow_Tag_Form").find("#tag_text").val("");                    },                    dataType:"text"            });        }        //删除标签        function del_tags(id)        {            $.ajax({                    type: ‘POST‘,                    url: ‘/follow/del_tag‘ ,                    data: "id="+id,                    success:function(result)                    {                        var tags_msg=jQuery.parseJSON(result);                        var html="<table class=‘table table-striped table-bordered table-hover‘ id=‘listtable‘>";                        html+="<tr><th>序号</th><th>项目名称</th><th>操作</th></tr>";                        var p=1;                        $.each(tags_msg,function(i,n)                        {                              html+="<tr><td>"+p+"</td><td>"+n.name+"</td><td> <a  onclick=‘del_tags("+n.id+");‘>删除</a></td></tr>";                            p++;                        } );                         html+="</table>";                        $("#Follow_Tag_Form").find("#Tags_list").html(html);                    },                    dataType:"text"            });        }        46.checkbox操作赋值:        //添加患者标签        function sel_tags_tag()        {            var arrChk=$("input[name=‘tags_checkbox‘]:checked");            var tags=‘‘;            $(arrChk).each(function(){                            tags+=$(this).attr("tag_name")+",";                        });            if(tags==‘‘)            {                alert(‘请选择患者标签!‘);                        return;            }            tags=tags.substring(0,tags.length-1);            $("#tags").val(tags);            $("#Tags_Form").modal(‘hide‘);        }        47. Javascript: unterminated string literal 解决方法:            $str = str_replace("\n", "", $str);            $str = str_replace("\r", "", $str);        48.js四舍五入保留两位小数:            var per=(((pass_count-count)/(total_count-count))*100).toFixed(2);        49.select动态添加生成:            var category=$("#item_category"+num).find("option:selected").text();                        $("#item_specialty"+num).empty();                        switch(category)                        {                            case "临床":                            $("#item_specialty"+num).append($("<option>").val("101").text("内科专业"));                            $("#item_specialty"+num).append($("<option>").val("102").text("外科专业"));                            $("#item_specialty"+num).append($("<option>").val("103").text("妇产科专业"));                            $("#item_specialty"+num).append($("<option>").val("104").text("儿科专业"));                            $("#item_specialty"+num).append($("<option>").val("105").text("其他专业"));                            break;                            case "中医":                            $("#item_specialty"+num).append($("<option>").val("201").text("中医"));                            break;                            case "口腔":                            $("#item_specialty"+num).append($("<option>").val("301").text("口腔"));                            break;                            case "公共卫生":                            $("#item_specialty"+num).append($("<option>").val("401").text("公共卫生"));                            break;                            case "人文医学":                            $("#item_specialty"+num).append($("<option>").val("501").text("人文医学"));                            break;                        }        50.延迟执行:            setTimeout("closediv()",2000);            function closediv()                {                    $(‘#mask‘).remove();                    $(‘#prompt‘).remove();                }        51.限制text只能输入数字:            onkeyup="if(this.value.length==1){this.value=http://www.mamicode.com/this.value.replace(/[^1-9]/g,‘‘)}else{this.value=this.value.replace(/D/g,‘‘)}"                                                  onafterpaste="if(this.value.length==1){this.value=http://www.mamicode.com/this.value.replace(/[^1-9]/g,‘0‘)}else{this.value=this.value.replace(/D/g,‘‘)}""color: #000000">.PHP对象json转string:            var msg_result=jQuery.parseJSON(JSON.stringify(<?php echo $msg;?>));        53.loader效果:            <div class="modal hide" id="loader_div">              <div class="modal-body">            <div id="loading" class="loading" style="display:none"><img src=http://www.mamicode.com/"http://patients.gooddr.com/theme/images/loader.gif"/> 数据加载中...
"color: #008000">//
搜索患者: function sel_datum() { var type=$("#type").val(); $.ajax({ type: ‘POST‘, url: ‘/report/patients_report‘ , data: "type="+type, beforeSend: function() { $("#loader_div").modal(); $("#loading").show(); }, success:function(result) { $("#loader_div").modal(‘hide‘); $("#loading").hide(); $("#page_content").html(result); }, dataType:"text" }); } 54.鼠标悬停"hand"(支持Chrome) onm ouseover="this.style.cursor=‘pointer‘;this.style.cursor=‘hand‘" onm ouseout="this.style.cursor=‘default‘" 55.select追加option: $("#convert_select").append("<option value=http://www.mamicode.com/‘"+pics.filename+"‘>"+pics.showname+"");

JS/Jquery常用代码1