zoukankan      html  css  js  c++  java
  • 前端基础之jQuery

     

    一、 jQuery是什么? 

    1、jQuery是由于世界各地的众多的javascript高手,为了让javascript使用起来更加方便、灵活封装原生javascript难以实现的众多功能开发出来优秀框架(库);

    作用

    1、它是轻量级的java script库(压缩后只有21k) ,这是其它的js库所不及的,它兼容CSS3,还兼容各种浏览器

    2、其宗旨是 write less do more 用最少的代码完成更多的功能

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>JS回顾</title>
        <style>
            *{margin: 0;padding: 0}
            div{height: 200px;background-color:pink;margin-bottom: 10px;display: none}
        </style>
        <script src="jquery-3.2.1.min.js"></script>
    </head>
    <body>
    <input id="bu" type="button" value="我是按钮">
    <div></div>
    <div></div>
    <div></div>
    </body>
    <script>
    //    window.onload=function () {
    //        document.getElementById('bu').onclick=function () {
    //         eles=document.getElementsByTagName('div')
    //            for(var i=0;i<eles.length;i++){
    //             eles[i].style.display='block';
    //             eles[i].style.innerText='我是内容'
    //                                           }
    //
    //                                                            }
    //                                        }
       //JavaScript的缺陷
    //   1、Windows.onload事件会被覆盖
    //   2、代码容错性差
    //   3、浏览器兼容性问题
    //   4、书写繁琐,代码量大
    //   5、代码乱
    
        $(document).ready(function () {
            $('#bu').click(function () {
                $('div').show().text('我是内容')
            })
        })
    </script>
    </html>
    View Code

    二、 什么是jQuery对象?

    1、JQuery库把所有的方法都封装在了一个JQuery对象里面,jQuery.()=$(),jQuery对象不同于docment对象

    (jQuery能实现的,JavaScript一定能实现,JavaScript能实现的功能,jQuery不一定能实现,因为jQuery是对JavaScript的封装。就像 Python和C的关系);

    2、JQuery的导入方法:<script src="zhanggen.js"></script>

    3、使用方法: $('选择器').(操作) (不管是CSS还是JavaScript还是jQuery都是一个套路,找标签,再做操作;)

    4、docment对象和JQuery对象之间的转换

    $(DOM对象)

    $(DOM对象)[0]

    三 、jQuery的选择器和筛选器

     

    1、基本选择器: $( 'ID、类、标签名')

    $("*") #全部选中  $("#id") #根据ID查找   $(".class") #根据类名  $("element") #根据标签名查找  $(".class,p,div")#多元素选择器
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <script src=jquery-3.2.1.min.js></script>
    </head>
    <body>
    </body>
    <p id="p1">hello word</p>
    <p class="p">p1</p>
    <p class="p">p2</p>
    <p class="p">p3</p>
    <script>
        $('#p1').css("color",'red')  //jquey对象的css 方法
        $('#p1').css({"color":'red','fontSize':'45px'})  //设置多个CSS属性,方法里传字典{}
        $(".p").css('color','red')  //jQuery对象的属性选择器,和JavaScript的区在于 找到标签集合无需for循环遍历即可批量处理
    
        li=[11,22,33,44]
        $.each(li,function (i,v) {
            if (v==33){return false}  //return false 结束整个循环
            console.log(i,v)
        })
    
        li1=['陈涛','高伦川','由秦兵','张跟']   ////return true值结束本次循环
        $.each(li1,function (i,v) {
            if (i==0){return true }
            console.log(i,v)
        })
    </script>
    </html>
    View Code

    2、层级选择器:子代、后代、毗邻、兄弟

    $(".outer div")空格隔开后代选择器    $(".outer>div") >子代     $(".outer+div")毗邻   $(".outer~div") 兄弟选择器
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>层级选择器</title>
    </head>
    <body>
    <div class="outer">
        <div class="inner">
            <p>p3</p>
        </div>
        <p>p2</p>
    </div>
    <p>p666</p>
    <script src="jquery-3.2.1.min.js"></script>
    <script>
    //      $('.outer p').css('color','red') //outer属性后代的所有的  P标签
    //      $('.outer>p').css('color','red') //outer 的子代  P标签
    //      $('.outer+p').css('color','red') //outer 的毗邻的 P标签
           $('.outer~p').css('color','red')  ////outer 的兄弟 标签
    </script>
    </body>
    </html>
    View Code

     3、属性选择器:$('[]')

    $('[id="div1"]')   $('["alex="sb"][id]')
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>属性选择器</title>
    </head>
    <body>
    <div name="zhanggen" class="c1">Helloween</div>
    <script src="jquery-3.2.1.min.js"></script>
    <script>
        $("[name='zhanggen'][class]").css('color','red')
    </script>
    </body>
    </html>
    View Code

     4、表单选择器:$(':text/chekbox')

    $("[type='text']")----->$(":text")         注意只适用于input标签  : $("input:checked")
    !DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>属性选择器</title>
    </head>
    <body>
    <input type="text" placeholder="用户">
    <div name="zhanggen" class="c1">Helloween</div>
    <script src="jquery-3.2.1.min.js"></script>
    <script>
        $("[name='zhanggen'][class]").css('color','red')
        $('[type="text"]').css('border','1px solid red')
        $(':text').css('border','1px solid green')  //简写形式
    </script>
    </body>
    </html>
    View Code

    5、获取所有cheked的value

       var selected_host_ids = [];
            var selected_host_eles = $("#host_groups ul").find(":checked");
            $.each(selected_host_eles,function (index,ele) {
                selected_host_ids.push($(ele).val())
            });
    View Code

    6、获取选中option的 text信息

     var $username = $('[name="username"]').find("option:selected").text();

    Jquery对象的筛选器(对选择器查找到的标签集合进行筛选)

    过滤筛选器:

    $("li").eq(2)  $("li").first()  $("ul li").hasclass("test")  $('box:even')
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <ul class="box">
        <li>1</li>
        <li>2</li>
        <li>3</li>
        <li>4</li>
        <li>5</li>
    </ul>
    
    <script src="jquery-3.2.1.min.js"></script>
    <script>
    //   $('.box li:eq(3)').css('color','red') //对ul标签下的li标签 筛选第3个
    //   $('.box li') .eq(2).css('color','red') //对ul标签下的li标签 筛选第2个
    //   $('.box li:lt(4)') .css('color','red') ///对ul标签下的li标签,筛选索引小于4 的li标签
    //   $('.box li:gt(2)') .css('color','red') //筛选索引大于 4 的li标签
    //   $('.box li:even').css('color','red')  //筛选索引 单数索引 的li标签
    //  $('.box li:odd').css('color','red')   //筛选索引 双数索引 的li标签
    
    </script>
    </body>
    </html>
    View Code

    关系查找筛选器:

     $("div").children(".test")   $("div").find(".test")   #查找所有子代
                                    
     $(".test").next()    $(".test").nextAll()    $(".test").nextUntil()  #向下查找兄弟标签
                               
     $("div").prev()  $("div").prevAll()  $("div").prevUntil()    #向上查找兄弟标签
                            
     $(".test").parent()  $(".test").parents()  $(".test").parentUntil()  #查找父级标签
    
     $("div").siblings() #查找兄弟表

    $(#province option:gt(0)).remove() #查找select标签中,除了第1个外的option子标签。
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <div class="c1">
        <div class="c3">
            <p>p4444</p>
            <div class="c4">
                <p class="p1">p1</p>
                <p>p4</p>
            </div>
        </div>
        <p>p2</p>
    </div>
    <div class="c2">
        <p>1111111111</p>
        <div>
            <p class="item" id="d1">p3
            <p>pppppppppppp</p>
            <p class="item" id="6">p4</p>
            <p class="item">p5</p>
            <p class="item" id="3">p6</p>
            <p class="item" id="d2">p7</p>
        </div>
    </div>
    
    
    <script src="jquery-3.2.1.min.js"></script>
    <script>
    
     //查找兄弟标签
    //    $('#d1').next().css('color','red').next().css('color','green') //基于当前标签向下 查找第1个兄弟标签 支持链式操作
    //    $('#d1').nextAll().css('color','red')                        //查找当前 标签下所有兄弟标签
    //     $('#d1').nextUntil('#3').css('color','red')            //查找当前标签下标签直到 找到id=3的标签为止(区间)
    //--------------------------------------------------------------------------------------------------------------------
    //$('#d2').prev().css('color','red')                ///基于当前标签向上查找
    //$('#d2').prevAll().css('color','red')
    //$('#d2').prevUntil('#6').css('color','red')
    
    //查找所有兄弟标签
    // $('#d1').siblings().css('color','red')
    //$('#d1').siblings().eq(2).css('color','red')
    
    //查找 子标签 find()查找所有子代  children 查找所有子代
    //$('.c1').children().css('color','red')
     // find()必须要有参数 注意
    //$('.c1').find('p').css('border','1px solid red')
    
     //查找父标签
    
    //$('.p1').parent().parent().css('color','red')
    
     $('.p1').parents().css('color','red')  //一直找到body
    
    </script>
    
    </body>
    </html>
    View Code

    JQuery的操作方法 

    四、Jquery对象的属性、CSS类、标签的文档操作(以上已经知道了,Jquery的选择器和筛选器可以找到标签了,以下主要讲述操作标签)

    Jquery绑定事件:

    页面载入

    $(document).ready(function(){alert(8989)}) // 当DOM载入就绪即可执行的事件 等同于 JS的 window.onload=function (){alert(666)}

    等同于

    事件绑定:

    $("p").click(function(){alert(123)})  // 切记和JS的docment对象区别 没有 on

    事件委派(实时动态得为新增的新标签对象,绑定事件)

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>jQuery绑定事件1</title>
    </head>
    <body>
    <div id="box">
        <div class="item">111</div>
        <div class="item">222</div>
        <div class="item">333</div>
    </div>
    <button id="add">add</button>
    <button id="del">解除事件</button>
    <script src="jquery-3.2.1.min.js"></script>
    <script>
    //    $('.item').click(function () {    //给box里面的div标签 绑定了 alert事件,问题是 新增加 button标签不会绑定
    //        alert('123')
    //    })
        $('button').click(function () {
            $('#box').append('<div class="item">9999</div>')
        })
    //                                             解决之道 换一种事件绑定方式  事件委派b绑定,就是通过父级标签,给子标签绑定事件
                                             //BBS多级评论会用
                                             //$(this)当前标签
        $('#box').on('click','.item',function () {
           alert($(this).index())
        })
        $('#del').click(function () {
            $('#add').off('click')
        })
    </script>
    </body>
    </html>
    View Code

    事件的切换: hover ( over, out ) 

    over:鼠标移到元素上要触发的函数

    out:鼠标移出元素要触发的函数

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>事件切换</title>
        <style>
            #a{background-color:red;height: 200px;width: 100px}
        </style>
    </head>
    <body>
    <div id="a">事件切换</div>
    </body>
    <script src="jquery-3.2.1.min.js"></script>
    <script>
        function a () {
            alert('欢迎进入')
        }
        function b(){
            alert("欢迎退出")
        }
        $('#a').hover(a,b)
    </script>
    </html>
    View Code

    属性操作

    attr操作自定义属性:自己在标签里定义的

    prop操作固有属性:标签里的固有属性  cheked,selected、id等。。。

    $('<option></option>').text(v.name).val(v.id).prop('selected',true);
    $("").attr();
    $("").removeAttr();
    $("").prop();
    $("").removeProp();
    --------------------------操作标签所属类
    $("").addClass(class|fn)
    $("").removeClass([class|fn])
    $(self).next().toggleClass("hide")
    //toggleClass 动态切换(有这个类删除,没有这个类增加,无需判断;)
    <script type="text/javascript">
    $(document).ready(function(){
      $(".btn1").click(function(){
      $("p").toggle();<!--点击1下P标签消失,再点击1下显示 -->
      });
    });
    </script>
    </head>
    <body>
    <p>This is a paragraph.</p>
    <button class="btn1">Toggle</button>
    </body>
    </html>
    toggle控制隐藏显示
     
    --------------------------HTML代码/文本/值
    $("").html([val|fn])
    $("").text([val|fn])
    $("").val([val|fn|arr])
    ---------------------------操作标签的CSS样式
    $("").css("color","red")
    $('th').css('text-align','center');
    $('td').css('text-align','center') ;
     1 <!DOCTYPE html>
     2 <html lang="en">
     3 <head>
     4     <meta charset="UTF-8">
     5     <title>Jquery对象的属性操作</title>
     6     <style>
     7         .di{width: 50px;height: 50px;background-color: #2459a2}
     8     </style>
     9 </head>
    10 <body>
    11 <form action="">
    12     <input type="text">
    13     <input type="password">
    14     <div class="div">
    15       <p class="a">123</p>
    16     </div>
    17     <div class="d"></div>
    18 
    19 </form>
    20 </body>
    21 <script src="zhanggen.js"></script>
    22 <script>
    23 
    24 //--------------Jquery对象的val取值方法-----------------
    25 //    Jquery对象的val方法 取input元素的值
    26     $(":text").val("2")
    27     $(":password").val("123")
    28 
    29 //------------------Jquery对象的attr取属性 和属性赋值操作------------------
    30 //    //Jquery的attr方法,取元素的自定义属性
    31 //    console.log( $('p').attr("class"))
    32      //Jquery的attr(属性,属性值)方法,修改元素的自定义属性
    33 //    console.log($('p').attr("name",'SB'))
    34 
    35     //Jquery的prop方法,取Jquery对象的固有属性
    36 //    console.log($(":text").prop("type",'password' ))
    37 
    38 //------------------Jquery对象的addClass(CSS属性)和属性------------------
    39 //一般用户CSS样式的添加
    40     $(".d").addClass("di")
    41 //------------------Jquery对象的removeClass(CSS属性)和属性------------------
    42      $("div").removeClass("di")
    43 
    44 
    45 //   text()方法去元素里的文本内容
    46 //    console.log( $('p').text())
    47 //   html()方法取出html代码 注意:如果元素没有包含其他元素返回该元素的文本
    48 //       console.log($('.div').removeClass("div"))
    49 
    50 
    51 
    52 </script>
    53 </html>
    View Code

    5、Jquery对象的2种for循环遍历方式(seach()方法)

    1、格式

    格式1:$.each(obj,fn)

    格式2:$("p").each(fn)

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>for循环</title>
    </head>
    <body>
    <ul class="li">
        <li typeof="q">1</li>
        <li class="it">2</li>
        <li >3</li>
    </ul>
    
    </body>
    <script src="zhanggen.js"></script>
    <script>
        var ares=["a",'b','c'];
        var arres1=["张根","hellow" ]
        var dic={"name":"张根","age":22}
    
    //// jQuery 第一种 for遍历循环方式  $.each(遍历对象,函数(参数1,参数2))参数1是索引值,参数2是元素;
    //    $.each(ares,function (i,j){
    ////        console.log(i)
    //        console.log(j)}  )
    //    Jquery的for循环遍历字典对象 i是键 j是值
    //  $.each(dic,function (i,j) {console.log(i,j)})
    
    //    $("ul li").each(function () {
    //        console.log($(this))
    //    })
    //jQuery 第二种 for遍历循环方式  $(this)指得数组中的元素  :
    // $(".li li").each(function () { if ($(this).hasClass("it")){
    //     console.log($(this).text())}} )
    
     $('.li li').each(function () {
         if ($(this).hasClass("it"))
         {console.log($(this).text() ) }
    
     } )
        
    </script>
    </html>
    View Code
      $('img').each(function () {
                $(this).attr('onerror', "this.style.display='none'");
            });
    隐藏显示故障图片
    $(self).siblings() .each(function () {
                $(this).removeClass('active').find('input[type="checkbox"]').attr("checked", false);
            });
    遍历标签

    2、退出 each 循环

    退出本次循环(return true ),退出整个循环(return false)

     li=[11,22,33,44]
        $.each(li,function (i,v) {
            if (v==33){return false}  //return false 结束整个循环
            console.log(i,v)
        })
    
        li1=['陈涛','高伦川','由秦兵','张某']   //return true值结束本次循环
        $.each(li1,function (i,v) {
            if (i==0){return true }
            console.log(i,v)
        })

    6、jQuery的对标签的操作

    1、创建标签:$(‘标签’)例: $("<p>")

    2、新增标签

    2.1:通过父标签 添加 子标签方法:append()、prepend()

      $('body').append($ele)
      var $ele2=$('<p></p>').text('p2')
      $('body').prepend($ele2)           //新增标签到 最前位置
      $('body').prepend('<p>111</p>')     //后来居上

    2.2:通过子标签 添加进 父标签 方法:after()、before()/appendTO()

     $('.outer').after($ele2)   //添加到 兄弟标签的后面
     $('.outer').before($ele)    //添加到 兄弟标签的前面
    $add_user_ele.appendTo('#form111')//通过子标签添加到父级标签里面
    
    

     2.3、通过兄弟标签添加 

     $('.outer').after($ele2)   //添加到 兄弟标签的后面
     $('.outer').before($ele)    //添加到 兄弟标签的前面

     



    $.trim($("#cmd").val());  //去除字符串的空格

    String.prototype.format = function () { //扩展js原型 字符串替换的方法 format
    var args = arguments;
    return this.replace(/{(d+)}/g, function (s, i) {
    return args[i];
    });
    };

    var
    $li_ele = $('<li></li>').addClass('list-group-item'); var a_ele = '<a href="/arya/cmdb/worker_order/see/?id={0}">{1}</a>'.format(k, v); ar $div_ele = $('<div></div>').addClass('pull-right'); var $handle_ico = '<a href="/arya/cmdb/worker_order/handle/?id={0}"><span class="glyphicon glyphicon-wrench" aria-hidden="true"></span></a>'.format(k) var $delete_ico = '<a style="margin-left: 20px" href="/arya/cmdb/worker_order/see/?flag=delete_work&amp;sub_id={0}&amp;wid=121"><span class="glyphicon glyphicon-trash" aria-hidden="true"></span></a>'.format(k)
                   $div_ele.append($handle_ico); $div_ele.append($delete_ico); $li_ele.append(a_ele); $li_ele.append($div_ele); $(
    '#Subtask_list_show').append($li_ele); $('#Create_failure').text("子任务添加成功。").css('color', 'green'); setTimeout("$('#Create_failure').text('').css('color','red')", 3000)

    3、替换方法:replaceWith(新标签)

    $('#h').replaceWith($ele2)

    4、克隆方法:clone()

    var $ele3=$('#h').clone()
    $('.outer').append($ele3)
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <script src="/static/jquery-3.2.1.min.js"></script>
        <script src="/static/bootstrap/js/bootstrap.min.js"></script>
        <script src="https://cdn.bootcss.com/bootstrap3-dialog/1.35.4/js/bootstrap-dialog.js"></script>
        <link rel="stylesheet" href="/static/bootstrap/css/bootstrap.css">
        <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap3-dialog/1.35.4/css/bootstrap-dialog.css">
    </head>
    <body>
    <div class="container">
        <div class="container">
            <div class="row" style="margin-top:50px">
                <div class="col-md-12 col-md-pull-0" id="zhanggen">
                    <form class="form-inline" id="default" account_key="default" style="margin-top: 60px">
                        <p>default</p>
                        <div class="form-group">
                            <label for="exampleInputEmail1">AccountID</label>
                            <input type="text" class="form-control" id="exampleInputEmail1" name="accountid"
                                   placeholder="账户ID" required>
                        </div>
    
                        <div class="form-group">
                            <label for="exampleInputPassword1">ClientID</label>
                            <input type="text" class="form-control" id="exampleInputPassword1" name="clientid"
                                   placeholder="客户ID" required>
                        </div>
                        <div class="form-group">
                            <label for="exampleInputPassword1">ClientSecret</label>
                            <input type="text" class="form-control" id="exampleInputPassword1" name="clientsecret"
                                   placeholder="客户安全码" required>
                        </div>
    
                        <div class="form-group">
                            <label for="exampleInputPassword1">IOS</label>
                            <input type="text" class="form-control" id="exampleInputPassword1" name="ios"
                                   placeholder="IOS" required>
                        </div>
                        <div class="form-group">
                            <label for="exampleInputPassword1">Android</label>
                            <input type="text" class="form-control" id="exampleInputPassword1" name="android"
                                   placeholder="Android" required>
                        </div>
                        <span class="glyphicon glyphicon-plus" aria-hidden="true" style="margin-left:30px"></span>
                    </form>
                </div>
    
            </div>
            <div class="row" style="margin-top: 20px">
                <div class="col-md-12 col-lg-offset-4">
                    <button class="btn btn-success" onclick="Submit_Multiple_Form()">提交</button>
                </div>
            </div>
            <div class="row" style="margin-top: 20px">
                <textarea id="display_json_data" class="form-control" rows="8" style="color: red"></textarea>
            </div>
        </div>
    </div>
    </body>
    <script>
        function open_dilog() {
            BootstrapDialog.show({
                message: '<input type="text" name="account" placeholder="请输入新的账户">',
                buttons: [{
                    label: '确认',
                    cssClass: 'btn-primary',
                    action: function (dialogItself) {
                        var $new_account = $('[ name="account"]').val();
                        if ($new_account) {
                            var $ele3 = $('#default').clone();
                            $ele3.attr({"account_key": $new_account});
                            $ele3.find('p').text($new_account);
                            $ele3.find('span').attr({'class': 'glyphicon glyphicon-minus minus'});
                            $ele3.appendTo('#zhanggen');
                            dialogItself.close();
                        }
                        else {
                            alert('请再次输入新的账号')
                        }
    
                    }
                }, {
                    label: '取消',
                    action: function (dialogItself) {
                        dialogItself.close();
                    }
                }]
            });
        }
    
        $('.glyphicon-plus').click(function () { //克隆form表单
            open_dilog();
        });
        $('#zhanggen').on('click', '.minus', function () {//删除form表单
            $(this).parent().remove()
        });
    
        function Submit_Multiple_Form() {
            var $Forms = $('#zhanggen form');
            var data = {};
            $Forms.each(function () {
                {
                    var account_key = ($(this).attr('account_key')); //账号也就是的第1个key
                    var $accountid = $(this [name = "accountid"]).val();
                    var $clientid = $(this [name = "clientid"]).val();
                    var $clientsecret = $(this [name = "clientsecret"]).val();
                    var $ios = $(this [name = "ios"]).val();
                    var $useractionsetid = {};
                    if ($ios) {
                        $useractionsetid["ios"] = $ios
                    }
                    var $android = $(this [name = "android"]).val();
                    if ($android) {
                        $useractionsetid["android"] = $android
                    }
                    var temp_dict = {
                        "accountid": $accountid,
                        "clientid": $clientid,
                        "clientsecret": $clientsecret,
                        "useractionsetid": $useractionsetid
                    };
                    data[account_key] = temp_dict
                }
            });
    
            console.log(JSON.stringify(data));
            $('#display_json_data').val(JSON.stringify(data));
    
            $.ajax({
                type: 'POST',
                dataType: 'json',
                contentType: 'application/json;charset=UTF-8',
                data: JSON.stringify(data),
                success: function (data, status) {
                    alert(data);
                }
    
            })
        }
    
    </script>
    
    </html>
    克隆代码
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <script src="/static/jquery/jquery-3.2.1.min.js"></script>
        <script src="/static/bootstrap/js/bootstrap.min.js"></script>
        <script src="https://cdn.bootcss.com/bootstrap3-dialog/1.35.4/js/bootstrap-dialog.js"></script>
        <script src="/static/jquery.cookie.js"></script>
        <link rel="stylesheet" href="/static/bootstrap/css/bootstrap.css">
        <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap3-dialog/1.35.4/css/bootstrap-dialog.css">
    </head>
    <body>
    <div class="container">
        <div class="row" id="form_zone">
            <div class="list-group" style="margin-top: 30px">
                <input type="text" style="margin-right:40%;" placeholder="用户" item="user">
                <span clone_user="true" class="glyphicon glyphicon-plus" aria-hidden="true" style="margin-left:30px"></span>
                <div class="list-group-item">
                    <input type="text" placeholder="key" item="key">
                    <input type="text" placeholder="value" item="value">
                    <span class="glyphicon glyphicon-plus" clone_item="true" aria-hidden="true"
                          style="margin-left:30px"></span>
                </div>
            </div>
        </div>
        <div class="row" id="submit_zone">
            <textarea id="display_json_data" class="form-control" rows="8" style="color: red"></textarea>
            <button onclick="make_json()" type="button" class="btn btn-success" style="margin-right: 30%">预览</button>
            <button onclick=" make_json()" type="button" class="btn btn-danger">提交</button>
        </div>
    </div>
    </body>
    <script>
        function add_item(slef) {
            var $parent = $(slef).parent().clone();
            var $grant_prent = $(slef).parent().parent();
            if ($(slef).attr('clone_item')) {
                $parent.find('span[clone_item="true"]').attr({'class': 'glyphicon glyphicon-minus minus'});
            }
            if ($(slef).attr('clone_user')) { // clone_user="true"
                $parent.find('span[clone_user="true"]').attr({'class': 'glyphicon glyphicon-minus minus'});
            }
    
            $parent.appendTo($grant_prent);
        }
    
        $('#form_zone').on('click', '.glyphicon-plus', function () {
            add_item(this)
        });
    
        $('#form_zone').on('click', '.minus', function () {//删除form表单
            $(this).parent().remove()
        });
    
        function make_json(is_submit) {
            var $inputs = $('[item="user"]');
            var data = {};
            $inputs.each(function (i, v) {
                var curent_user = $(v).val();
                data[curent_user] = {};
                make_dict($(v), data, curent_user);
            });
            $('#display_json_data').val(JSON.stringify(data))
        }
    
        function make_dict($ele, data, curent_user) {
            var $list_group_item = $ele.parent().children('.list-group-item');
            $list_group_item.each(function (i, v) {
                var item_key = $(v).children('[item="key"]').val();
                var item_value = $(v).children('[item="value"]').val();
                data[curent_user][item_key] = item_value;
            });
        }
    
    
    </script>
    </html>
    克隆form表单生成json数据

    5、删除方法:remove()

    $('#h').remove()  //清空标签
    $('#h').empty() //清空标签中的内容
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>节点的操作</title>
        <script src="jquery-3.2.1.min.js"></script>
    </head>
    <body>
    <div class="outer">
      <h1 id="h">标题</h1>
    </div>
    <script>
    //  var $ele=$('<p></p>').text('p1')   //新增标签到 最后位置
    //  var $ele2=$('<p></p>').text('pppp')
    //  //通过父标签 添加 子标签
    //  $('body').append($ele)
    //  var $ele2=$('<p></p>').text('p2')
    //  $('body').prepend($ele2)           //新增标签到 最前位置
    //  $('body').prepend('<p>111</p>')     //后来居上
    //
    ////通过子标签 添加到父标签
    // $ele.appendTo('body')
    // $ele2.prependTo('body')
    //
    //通过兄弟标签添加 新标签
    //  $('.outer').after($ele2)   //添加到 兄弟标签的后面
    // $('.outer').before($ele)    //添加到 兄弟标签的前面
    //
    //  通过新标签 直接插入到 兄弟标签下
    // $ele2.insertBefore('div')  //后面
    // $ele.insertAfter('div')    //前面
    
    //替换
    //$('#h').replaceWith($ele2)
    
    //克隆
    //var $ele3=$('#h').clone()
    //    $('.outer').append($ele3)
    
    //删除
    //$('#h').remove()  //清空标签
    //$('#h').empty() //清空标签中的内容
        
    </script>
    </body>
    </html>
    View Code

    六 动画效果及回调函数

    1、显示与隐藏方法:hide()、show()

    $("img").hide()

    $("img").show()

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <style>
            *{margin: 0}
            /*.box{background-color: blue; 100px;height: 100px}*/
        </style>
    </head>
    <body>
    <img src="1.jpg" alt="">
    <button class="c1">隐藏</button>
    <button class="c2">显示</button>
    <button class="c3">切换</button>
    
    <div class="box"></div>
    </body>
    
    <script src="jquery-3.2.1.min.js"></script>
    <script>
        //显示与隐藏 切换 hide show  toggle
        $('.c1').click(function () {
            $('img').hide()
        } );
        $('.c2').click(function () {
            $('img').show()
        });
        $('.c3').click(function () {
            $('img').toggle()
        })
     </script>
    View Code

    2、操作莫泰对话框显示与隐藏 

    $('#mymodal').modal('hide')

    $('#mymodal").modal('show')

    3、淡入淡出方法: fadein()、fadeout()

    $('img').fadeIn(2000)

    $('img').fadeOut(1000)

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>淡入淡出</title>
        <script src="jquery-3.2.1.min.js"></script>
    </head>
    <body>
    <img src="1.jpg" alt="">
    <button id="in">淡入</button>
    <button id="out">淡出</button>
    <button id="toger">切换</button>
    </body>
    <script>
        $('#in').click(function () {
            $('img').fadeIn(2000)
        })
        $('#out').click(function () {
            $('img').fadeOut(1000)
        })
        $('#toger').click(function () {
            $('img').fadeToggle()
        })
    </script>
    </html>
    View Code

     

    七、jQuery的状态事件 

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <script src="jquery-3.2.1.min.js"></script>
    </head>
    <body>
    <input type="text">
    <script>
        $('input').keydown(function (e) {    //绑定一个键盘按下事件,通过e就是获取 事件状态(在键盘上输入了那些字母的acci)
            console.log(e.keyCode)
        })
        $(document).click(function (e) {       //给整个document绑定一个 点击就可以 通过事件状状态查看 点击位置的 x,y坐标
            console.log(e.clientX,e.clientY)
        })
    </script>
    </body>
    </html>
    View Code

    八、jQuery操作标签位置 和滚动条

    获取标签位置和标签偏移方法:  offset()、postion()

    1、$('.box2').offset({left:400,top:0})

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>元素偏移</title>
        <style>
            *{margin: 0}
            .box1{width: 200px;height: 200px;background-color: blue}
            .box2{width: 200px;height: 200px;background-color: red}
        </style>
        <script src="jquery-3.2.1.min.js"></script>
    </head>
    <body>
    <div class="box1"></div>
    <div class="box2"></div>
    <button>偏移</button>
    <script>
        $('button').click(function () {
            $('.box2').offset({left:400,top:0})
        })
    </script>
    </body>
    </html>
    View Code

     盒子跟随鼠标移动案例

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <style>
            *{margin: 0}
            .box{width: 200px;height: 200px;background-color: red}
        </style>
        <script src="jquery-3.2.1.min.js"></script>
    </head>
    <body>
    <div class="box"></div>
    </body>
    <script>
        $('.box').mousedown(function (e) {
            var mouse_x=e.clientX
            var mouse_y=e.clientY
    
            $(document).mousemove(function (e) {
               $('.box').offset({left:e.clientX,top:e.clientY})
            })
             $(document).mouseup(function () {
            $(document).off()
        })
        })
    
    </script>
    </html>
    View Code

    2、$('.box').postions()  

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <style>
            *{margin: 0}
            .box1{width: 200px;height: 200px;background-color: #2aabd2}
            .box2{width:200px;height: 200px;background-color: #1b6d85 }
            .outer{position: relative}
        </style>
        <script src="jquery-3.2.1.min.js"></script>
    </head>
    <body>
    <div class="box1"></div>
    <div class="outer">
        <div class="box2"></div>
    </div>
    
    <script>
        console.log($('.box1').position().top)   //postion()方法和offset()方法一致,都是获取标签的位置 top、left
                                                     // 区别在于 postion参照 已经定位父级标签(如果没有会一直找到body)
                                                     // offset()方法参照 整个视口
        console.log($('.box2').position().left)
         console.log($('.box2').position().top)
    </script>
    </body>
    </html>
    View Code

    3、offset()和postions()方法的区别

    offset()方法获取位置标签位置参照的是整个可视窗口,而postions()方法参照的是已定位的父级标签,如果没有会以body标签为参照

    获取滚动条的位置,返回顶部: $(window).scrollTop(0) 方法   

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <style>
            .box{background-color: #2aabd2; width: 100%;height: 2000px}
            #returntop{
                           position: fixed;
                            bottom: 20px;
                            right: 20px;
                            width: 70px;
                            height:40px;
                            background-color: whitesmoke;
                            color:rebeccapurple;
                            display: none;
                            }
        </style>
        <script src="jquery-3.2.1.min.js"></script>
    </head>
    <body>
    <div class="box"></div>
    <button id="returntop">返回顶部</button>
    <script>
        $(window).scroll(function () {
            console.log($(window).scrollTop())   //注意获取滚动条 的位置应该绑定事件给window对象绑定scroll事件,
                                                     // 操作$(window)对象的scrollTop()方法
            if($(window).scrollTop()>1000){$('#returntop').show().click(function () {
                $(window).scrollTop(0) })}
            else {$('#returntop').hide()}
        })
    </script>
    </body>
    </html>
    View Code

     

    8、获取document对象的 scrollTop()值

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>滚动条</title>
        <script src="jquery-3.2.1.min.js"></script>
        <style>
            div{
                background-color:#e4b9b9;
                width: 200px;
                height: 200px;
                overflow: scroll;
               }
            button{width: 30px;height: 30px;background-color: #e4b9b9;color: #0f0f0f;display: none}
        </style>
    </head>
    <body>
    <div>
        <h1>张根</h1>
        <h1>张根</h1>
        <h1>张根</h1>
        <h1>张根</h1>
        <h1>张根</h1>
        <h1>张根</h1>
        <h1>张根</h1>
        <h1>张根</h1>
        <h1>张根</h1>
        <h1>张根</h1>
        <button>top</button>
    </div>
    
    </body>
    <script>
        $('div').scroll(function () {
               if($('div').scrollTop()>400){$('button') .show().click(function () {
                   $('div').scrollTop(0)
               })}
        })
    </script>
    </html>
    View Code

    九、jQuery获取 盒子的尺寸

            $("").height()       //获取盒子文本区域的  长度和宽度
            $("").width()
    
            $("").innerHeight() //获取文本区域+padding填充区域+边框 的长度和宽度
            $("").innerWidth()
    
            $("").outerHeight() //获去整个盒子的 长度和宽度
            $("").outerWidth()
         
         
            $("").outerHeight(ture) //获取盒子+magin外边距的长度和宽度
         
             $("").outerHeight(ture)

          
    
    
       
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <style>
            .box {
                width: 200px;
                height: 200px;
                background-color: green;
                padding: 50px;
                border: 10px red solid;
                    }
         </style>
        <script src="jquery-3.2.1.min.js"></script>
    </head>
    <body>
    <div class="box">张根</div>
    </body>
    <script>
     console.log($('.box').width())  //获取文本区域的长度 和宽度
     console.log($('.box').height())
    
     console.log($('.box').innerHeight()) //获取盒子不带边框的 长度 和宽度
     console.log($('.box').innerWidth())
    
     console.log($('.box').outerHeight())  //获取盒子整体长度 和宽度
    console.log($('.box').outerWidth())
    </script>
    </html>
    View Code

     十、扩展jquery方法

    jQuery是一个优秀的JavaScript框架,但是如果想要在这个框架基础上扩展自己的方法也是可以的;

     jqury.extend()方法

    //扩展jquery的方法
        jq.extend({
            'nBlist': function (url) {
                requesturl = url;
                inint(1);
                bindSearchConditionEvent();
            },
            "changePage": function (pageNum) {
                init(pageNum);
            }
    
    
        })
    View Code

     十一、补充

    1、formData(二进制传输)

    form表单可以上传文本内容给Django,可是如果是图片、视频、文件如何上传呢?

    $('#handle').click(function () {
                var enclosure_formData = new FormData();
                var $picture1 = $('[name="picture1"]')[0].files[0];
                var $picture2 = $('[name="picture2"]')[0].files[0];
                var $picture3 = $('[name="picture3"]')[0].files[0];
                var $file1 = $('[name="file0"]')[0].files[0];
                var $csrf=$('[name="csrfmiddlewaretoken"]').val();
                var $verbose_content = $('[name="content"]').val();
    
                enclosure_formData.append("csrfmiddlewaretoken", $csrf);
                enclosure_formData.append("file1", $file1);
                enclosure_formData.append("picture1", $picture1);
                enclosure_formData.append("picture2", $picture2);
                enclosure_formData.append("picture3", $picture3);
                enclosure_formData.append("verbose_content", $verbose_content);
    
                 $.ajax({
                    url: '/arya/cmdb/worker_order/exchange/?wid={{worker_order_id}}',
                    type: "POST",
                    processData: false,
                    contentType: false,
                    data: enclosure_formData,
                    success: function (data) {
                        if (data=="ok"){
                            location.href="/arya/cmdb/worker_order/exchange/?id={{worker_order_id}}"
                        }
    
                    }
    
    
                })
                
                
                
            });
    fromData使用

    Django后端接收文件

    后端数据库如果接收到文件数据,如何存储在数据库呢?

        def exchange_view(self,request): #工单分配视图
            if request.method=='POST':
                wid=request.GET.get('wid')
                verbose_content=request.POST.get('verbose_content')
                file1=request.FILES.get('file1')
                picture1=request.FILES.get('picture1')
                picture2 = request.FILES.get('picture2')
                picture3 = request.FILES.get('picture3')
                current_order=models.Worker_order.objects.filter(pk=wid).first()
    
                logs={"verbose_content":verbose_content,"file1":file1,
                      "picture1":picture1,"picture2":picture2,"picture3":picture3,
                      "update_time":datetime.datetime.now(),"details":'处理内容'
    
                      }
                log_id = models.Worker_order_details.objects.create(**logs).pk
                current_order.logs.add(log_id)
                current_order.save()
                return HttpResponse('ok')
    
            worker_order_id=request.GET.get('id')
            worker_order_obj=models.Worker_order.objects.filter(pk=worker_order_id).first()
            desc = mark_safe(worker_order_obj.desc.replace("
    ", "<br/>"))
            logs = worker_order_obj.logs.all()
            return render(request,'woke_order/exchange.html',locals())
    request.FILES
    class Worker_order_details(models.Model):
        '''
        工单变更记录表
        '''
        details=models.TextField(verbose_name='verbose_name="工单变更内容')
        update_time=models.CharField(max_length=255,verbose_name="更新时间")
        verbose_content=models.CharField(max_length=255,verbose_name="变更说明")
        file1=models.FileField(verbose_name='文件', upload_to='upload/files/',default=None,null=True,blank=True)
        picture1 = models.FileField(verbose_name='图片1', upload_to='upload/pictures/',default=None,null=True,blank=True)
        picture2 = models.FileField(verbose_name='图片2', upload_to='upload/pictures/',default=None,null=True,blank=True)
        picture3 = models.FileField(verbose_name='图片3', upload_to='upload/pictures/',default=None,null=True,blank=True)
        picture4 = models.FileField(verbose_name='图片4', upload_to='upload/pictures/',default=None,null=True,blank=True)
    models的upload_to='uel'参数

     

    十二、moment.js 获取时间插件 http://momentjs.cn/docs/

     $('[name="startdate"]').val(moment().format('YYYY年MM月DD日HH时mm分ss秒'));                                 //获取当前时间
     var $cost_number = parseInt($('[name="WorkTime_cost"]:checked').val()) + 1;
     $('[name="enddate"]').val(moment().add($cost_number, 'hour').format('YYYY年MM月DD日HH时mm分ss秒'));        //获取未来时间

    十三 、jQuery常用插件

    1.表单验证插件( jQuery Validation)

    基本使用

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <!--<script src="http://static.runoob.com/assets/jquery-validation-1.14.0/lib/jquery.js"></script>-->
        <!--<script src="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/jquery.validate.min.js"></script>-->
        <script src="jquery-validation-1.14.0/lib/jquery.js"></script>
        <script src="jquery-validation-1.14.0/dist/jquery.validate.min.js"></script>
        <script src="jquery-validation-1.14.0/dist/additional-methods.min.js"></script>
        <script src="jquery-validation-1.14.0/dist/localization/messages_zh.min.js"></script>
    </head>
    <body>
    <form method="post" id="form1">
        <p>姓名:<input type="text" name="title"></p>
        <p>年龄:<input type="text" name="age"></p>
        <p>邮箱:<input type="text" name="email"></p>
        <p>博客:<input type="text" name="bolg_addr"></p>
        <p>手机:<input type="text" name="phon"></p>
        <p>手机:<input type="text" name="phon1"></p>
        <p>验证码:<input type="text" name="code"></p>
        <p>文件:<input type="file" name="files"></p>
    
    
        <p><input type="submit"></p>
    </form>
    </body>
    <script>
        $('#form1').validate({
            rules: {
                title: {
                    required: true,      //不能为空
                    minlength: 6,         //输入最小长度限制
                    maxlength: 10,         //输入最大长度限制
                    rangelength: [6, 10]  //输入长度在 6-10之间
    
                },
    
    
                age: {
                    required: true,
                    number: true,          //必须输入数字
                    digits: true,          //必须输入整数
                    min: 18,                 //输入数字必须大于18
                    max: 100,                 //输入数字必须小于100
                    range: [18, 100]          //输入数字在某区间范围
    
    
                },
                email: {
                    required: true,
                    email: true         //必须输入正确的邮箱格式
    
                },
                bolg_addr: {
                    required: true,    //输入正确的url http://www.xxxx.com
                    url: true
    
    
                },
    
                phon1: {
                    required: true,
                    equalTo: 'input[name="phon"]' //phon1 和phon1输入必须一致
    
                },
    //        code:{
    //            remote:'/code/', //通过ajax把 输入的内容发送给后端
    //            type:'post',
    //            data:{}
    //        },
                files: {
                    extension: 'css|html'//限制上传文件的类型
                }
            },
            messages: {          //字符串替换 定制错误信息{0} 和上面设置的长度保持一致(避免验证规则修改,忘记修正错误提示信息)
                title: {
                    required: '不能为空',
                    minlength: '输入最小长度为{0}',
                    maxlength: '输入最大长度为{0}',
                    rangelength: '输入字符串长度在{0}到{1}之间'
    
                }
    
            }
    
        })
    </script>
    </html>
    基本使用

    validate()方法配置选项

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <script src="jquery-validation-1.14.0/lib/jquery.js"></script>
        <script src="jquery-validation-1.14.0/dist/jquery.validate.min.js"></script>
        <script src="jquery-validation-1.14.0/dist/additional-methods.min.js"></script>
        <script src="jquery-validation-1.14.0/dist/localization/messages_zh.min.js"></script>
    </head>
    <body>
    
    <form method="post" id="form1">
        <p>姓名:<input type="text" name="title"></p>
        <p>年龄:<input type="text" name="age"></p>
        <p><input type="submit"></p>
    </form>
    <div id="info" style="display: none">有错误啦!:((</div>
    <div id="info1"></div>
    </body>
    <script>
        $('#form1').validate({
            rules: {
                title: {
                    required: true,      //不能为空
                    rangelength: [6, 10]  //输入长度在 6-10之间
    
                }
            },
            messages: {          //字符串替换 定制错误信息{0} 和上面设置的长度保持一致(避免验证规则修改,忘记修正错误提示信息)
                title: {
                    required: '不能为空',
                    rangelength: '输入字符串长度在{0}到{1}之间'
    
                }
    
            },
            submitHandler: function (form) {                  //验证通过执行回调函数
                console.log(':))');
                return true                                  //return true form表单才可以提交
            },
            invalidHandler: function (event, invalidator) {    //验证失败执行的回调函数
                console.log(':((')
            },
            errorClass: 'NO',//验证失败之后input和lable错误提示标签的类名(可以为错误信息添加样式)
            validClass: 'YES',//验证成功之后input标签的类名
            errorElement: 'lable', //用什么标签 显示错误提示信息? 默认lable标签
            wrapper: 'div',//给以上标签设置 装饰标签
    
            errorPlacement: function ($error, element) { //修改错误提示信息标签的位置;$error:错误提示的lable标签,element当前input标签
                $error.insertAfter(element);
            },
            errorContainer: '#info1', //验证错误时 显示标签,验证成功隐藏标签
    //        errorLabelContainer:'#info1',//把所有错误信息,显示在一个标签里面
            success: function ($lable, element) {//每个input标签验证成功之后执行的函数(验证成功之后,重点给错误信息加效果)
    //         和unhighlight区别:修改提示信息
                $lable.text('验证通过')
            },
            highlight: function (element, errorClass, validClass) { //验证失败执行的函数
                $(element).css('background-color', 'red')
            },
            unhighlight: function (element, errorClass, validClass) { //验证成功执行的函数(验证成功之后,重点给input信息加效果)
                $(element).css('background-color', 'green')
                //和success区别:表单控件
            },
            //调试模式----------------------------------->
    //        ignore:'[name="title"]'//设置不做验证的input标签(调试模式试用)
    //        debug:true,  //调试模式试用,true不会向后台提交(调试模式试用)
    
        })
    </script>
    </html>
    
    验证时常有方法
    validate(配置选项)

    validator对象的方法

    validator对象就是validate()方法执行后return的结果

    <script type="text/javascript">
            $(function () {
                var Validator = $('#form1').validate({
                    rules: {
                        title: {
                            required: true,      //不能为空
                            rangelength: [6, 10]  //输入长度在 6-10之间
    
                        }
                    },
                    invalidHandler: function (event, invalidator) {    //验证失败执行的回调函数
                       console.log('对不起您有'+ Validator.numberOfInvalids()+'表单控件没有通过验证')
                    }
                });
    
                $('button.form').click(function () {
                    console.log(Validator.form())                            //验证form表单是否验证通过?return true和false
                });
                $('button.element').click(function () {
                    console.log(Validator.element('[name="title"]'))      //验证form表单里面单个input是否通过?return true和false
                });
                $('button.resetForm').click(function () {                //把前面验证的 FORM 恢复到验证前原来的状态
                    Validator.resetForm();
                });
                $('button.showErrors').click(function () {              //显示特定的错误信息
                    Validator.showErrors({
                        title: "自定义错误信息"                           
                    });
                });
                //Validator.numberOfInvalids 有X个表单控件没有通过验证!
    
    
            });
        </script>
    Validator方法

    jQueryValidation的静态方法

    可以直接在全局调用的方法

      $.validator.setDefaults({                    //改变默认配置
                    debug: true
                });
    $.validator.setDefaults({改变默认配置})
       $.validator.addClassRules({                 //通过标签的class为标签批量设置验证规则
                    zhanggen: {
                        required: true,
                        rangelength: [2, 10]
                    }
                });
    $.validator.addClassRules({//通过标签的class为标签批量设置验证规则})
    var urls = [                              //$.validator.format()模板替换
                    {url: "http:www.baidu.com", title: "百度"},
                    {url: "http:www.taobao.com", title: "淘宝"},
                    {url: "http:www.qq.com", title: "腾讯"}
                ];
    
                var html = '';
                tem = $.validator.format("<div><a href='{0}'>{1}</a></div>");
                for (var i = 0; i < urls.length; i++) {
                    html += tem(urls[i].url, urls[i].title)
                }
                $('body').append(html);
    $.validator.format()模板替换
    $.validator.addMethod('zhanggen', function (value, element, args) {  //$.validator.addMethod(验证名称,验证逻辑,错误提示)------>自定制验证规则
                    //console.log(value) 验证控件输入的值
                    //console.log(element) 验证控件本身
                    //console.log(args)   使用该规则时,传入的参数。
    
                    if(args){
                        return /^[a-zA-Z_][a-zA-Z_0-9]*/.test(value); //符合正则条件返回true否则false
                    }
                    else{return true}
    
                }, '返回{0},自定制规则未通过!');
    自定义验证规则

    rules方法

    rules方法可以动态得查看、增加、删除 input输入框的验证规则

     console.log($('[name="title"]').rules())               //查看input控件的验证规则
    查看
    $('[name="title"]').rules('add',{min:10,max:100}); 
    增加
      $('[name="title"]').rules('remove','min max');      //删除input控件的验证规则
    删除

    valid方法

    验证form表单是否验证成功!

    console.log($('#form1').valid())                 //检查表单是否验证成功?返回比尔值
    valid()

    综合案例

    #register {
        margin:100px auto 100px auto;
        border:1px solid #cacaca;
        padding:35px 10px 20px 30px;
        width:765px;
        font-size:13px;
    }
    #register div.row {
        margin:10px 0;
    }
    #register div.row div.text {
        float:left;
        width:80px;
    }
    #register div.row input.text {
        width:280px;
        height:18px;
        border:1px solid #ccc;
    }
    #register div.row input.photo {
        width:280px;
    }
    #register div.row select {
        border:1px solid #ccc;
    }
    #register div.row input.submit {
        width:40px;
        height:30px;
        border:none;
    }
    .error {
        background:url(unchecked.gif) 0px center no-repeat;
        padding-left:20px;
        margin-left:20px;
    }
    .ok {
        background:url(checked.gif) 0px center no-repeat;
        padding-left:20px;
        margin-left:20px;
    }
    formCSS样式
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <script src="jquery-validation-1.14.0/lib/jquery.js"></script>
        <link rel="stylesheet" href="form.css">
        <script src="jquery-validation-1.14.0/dist/jquery.validate.min.js"></script>
        <script src="jquery-validation-1.14.0/dist/additional-methods.min.js"></script>
        <script src="jquery-validation-1.14.0/dist/localization/messages_zh.min.js"></script>
        <script>
            $(function () {
                Array.prototype.is_in = function (e) {  //扩展arry的成员判断方法
                    var r = new RegExp(',' + e + ',');
                    return (r.test(',' + this.join(this.S) + ','));
                };
                $('#register').validate({
                    submitHandler: function (form) {
                        alert('恭喜验证成功');
                        return true
                    },
                    invalidHandler: function (event, invalidator) {
                        alert('对不起,您有' + invalidator.numberOfInvalids() + '个字段未验证成功!')
                    },
                    rules: {
                        username: {required: true, rangelength: [2, 6]},
                        sex: {required: true},
                        email: {required: true, email: true},
                        love: {required: true},
                        fruit: {required: true, minlength: 2},//minlength至少选择2项
                        photo: {required: true, extension: 'jpg|jpeg|gif|png'},
                        agreement: {required: true}
                    },
                    messages: {
                        username: {
                            required: '亲!用户名必须填写!',
                            rangelength: '亲!亲讲用户名长度控制在{0}到{1}之间!'
                        },
                        sex: {
                            required: "亲!您是美女还是帅哥!"
                        },
                        email: {
                            required: "亲!请填写您的邮箱地址!",
                            email: "亲!邮箱地址不正确!"
                        },
                        love: {
                            required: "亲!请至少选一个您喜爱的运动!"
                        },
                        fruit: {
                            required: "亲!请选择您喜爱的水果!",
                            minlength: "亲!请至少选择{0}种喜爱的水果!"
                        },
                        photo: {
                            required: "亲!请传一个您尊贵的头像!",
                            extension: '亲!请选择以下这几种后缀名的图片:jpg|jpeg|gif|png'
                        },
                        agreement: {
                            required: "亲!必须要遵循我们的协议才能够注册!"
                        }
                    },
                    errorPlacement: function ($error, element) { //修改错误提示信息标签的位置;$error:错误提示的lable标签,element当前input标签
                        var selectANDcheckbox = ['sex', "love", 'agreement'];
                        if (selectANDcheckbox.is_in($(element).attr('name'))) {
                            $(element).parent().parent().append($error)
                        }
                        else {
                            $error.insertAfter(element);
                        }
                    },
                    highlight: function (element, errorClass, validClass) { //失败后修改错误提示信息的样式
                        $(element).css('border-color', 'red');
                        $(element).parents('#register .row').find('.' + errorClass).removeClass('ok');
                    },
                    success: function (label, element) {                  //成功后修改错误提示信息的样式
                        label.addClass('ok');
                        $(element).css('border-color', '#ccc');
                    }
                })
            })
        </script>
    </head>
    <body>
    <form id="register">
        <div class="row">
            <div class="text">用户名:</div>
            <input class="text" type="text" name="username"/>
        </div>
        <div class="row">
            <div class="text">性别:</div>
            <div class="radio">
                <label>
                    <input type="radio" name="sex"/></label>
                &nbsp;
                <label>
                    <input type="radio" name="sex"/></label>
            </div>
        </div>
        <div class="row">
            <div class="text">邮箱:</div>
            <input class="text" type="text" name="email"/>
        </div>
        <div class="row">
            <div class="text">体育爱好:</div>
            <div class="checkbox">
                <label>
                    <input type="checkbox" name="love"/>足球
                </label>
                &nbsp;
                <label>
                    <input type="checkbox" name="love"/>篮球
                </label>
                &nbsp;
                <label>
                    <input type="checkbox" name="love"/>乒乓球
                </label>
                &nbsp;
                <label>
                    <input type="checkbox" name="love"/>羽毛球
                </label>
            </div>
        </div>
        <div class="row">
            <div class="text">水果爱好:</div>
            <select name="fruit" multiple="multiple">
                <option value="苹果">苹果</option>
                <option value="鸭梨">鸭梨</option>
                <option value="香蕉">香蕉</option>
                <option value="椰子">椰子</option>
            </select>
        </div>
        <div class="row">
            <div class="text">头像:</div>
            <input type="file" class="photo" name="photo"/>
        </div>
        <div class="row">
            <div class="text">注册协议:</div>
            <div class="checkbox">
                <label>
                    <input type="checkbox" name="agreement"/>同意
                </label>
            </div>
        </div>
        <div class="row">
            <div class="text">&nbsp;</div>
            <input class="submit" type="submit" name="submit" value="提交"/>
        </div>
    </form>
    </body>
    </html>
    模板

    2.表单提交插件 (jQueryForm)

    submit提交表单会刷新,而ajax提交操作繁琐,所以 jQueryForm应运而生了

    基本使用

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>测试</title>
        <script src="/static/jquery-3.2.1.min.js"></script>
        <script src="/static/plugin/jquery.form.min.js"></script>
        <script>
            $(function () {
                $('#from1').ajaxForm()
            })
        </script>
    </head>
    <body>
    <form action="/test/" method="post" id="from1">
        <p>姓名:<input type="text" name="name"></p>
        <p>性别:男<input type="radio" name="gender"><input type="radio" name="gender">
        </p>
        <p>爱好:学习<input type="checkbox" name="holby" checked value="0">
            跑步<input type="checkbox" name="holby" value="1">
            唱歌<input type="checkbox" name="holby" value="2">
        </p>
        <p><input type="submit" value="提交"></p>
    </form>
    </body>
    </html>
    $('#from1').ajaxForm()
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>测试</title>
        <script src="/static/jquery-3.2.1.min.js"></script>
        <script src="/static/plugin/jquery.form.min.js"></script>
        <script>
            $(function () {
                //$('#from1').ajaxSubmit() ajaxForm实在点击submit按钮之后增加的事件,而ajaxSubmit()则会直接提交,参数和ajaxForm一致
                $('#from1').ajaxForm({
                    beforeSerialize: function ($form, options) {        //在提交之前执行的函数
                        var gender = $form.find('[name="gender"]:checked').val();
                        if (gender == '2') {
                            alert('对不起您不能登录!');
                            return false
                        }                                               //注意return false之后表单无法提交
                        else {
                            return true
                        }
                    },
                    success: function (data, status, jqXHR, form) {   //服务器响应成功之后执行的回调函数
                        $(data).appendTo('#div1')                   //服务器响应标签,直接添加
                    },
                    //resetForm:true,                                  //服务器响应之后清空input中内容
                    //clearForm:true,
                      //target:'#div1',                                  //把服务器响应的内容,放到某个标签里面
                     //replaceTarget:false                              //是否替换标签本身
    
                })
            })
        </script>
    </head>
    <body>
    
    <form action="/test/" method="post" id="from1">
        <p>姓名:<input type="text" name="name"></p>
        <p>性别:男<input type="radio" name="gender" value="0"><input type="radio" name="gender" value="1">
            变性<input type="radio" name="gender" value="2">
        </p>
        <p>爱好:学习<input type="checkbox" name="holby" checked value="0">
            跑步<input type="checkbox" name="holby" value="1">
            唱歌<input type="checkbox" name="holby" value="2">
        </p>
        <div id="div1">
    
        </div>
        <p><input type="submit" value="提交"></p>
    </form>
    </body>
    </html>
    进阶

    3.input输入框自动提示插件(Ajax AutoComplete for jQuery)

    概述:Ajax AutoComplete for jQuery插件,我们直接简称为AutoComplete插件,通过它我们可以轻松地实现自动完成功能!

    网址:https://www.devbridge.com/sourcery/components/jquery-autocomplete/

    效果:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <script src="/static/jquery-3.2.1.min.js"></script>
        <link rel="stylesheet" href="/static/plugin/jqueryautocomplete/styles.css">
        <script src="/static/plugin/jqueryautocomplete/jquery.autocomplete.min.js"></script>
        <script>
            $(function () {
                $('[name="user"]').autocomplete({
                    {#                lookup:["张根","善良","帅哥"],           //用户输入时提示的信息,直接在本地获取!#}
                    serviceUrl: '/SearchHistory/',                        //用户输入时提示的信息,从后台获取!(注意后端必须返回json格式数据)
                    onSelect: function (suggestion) {
                        $('#form1').submit()                                 //用户选中提示信息之后执行的函数
                    },
                    minChars: 0,                                             //用户输入多少个字符之后,提示。
                    paramName: 'q',                                          //设置项服务器端发送请求的参数名称
                    type: 'get',                                             //请求方式(默认为GET)
                    {#                deferRequestBy:1000,                                   //如果介意用户输入之后就想服务器端发送请求,可以设置请求的延时的时间(毫秒)#}
                    noCache: false,                                         //缓存提示信息。(默认缓存)
                    formatResult: function (suggestion, currentValue) {       //每条提示信息从后端返回,都会执行formatResult为提示信息增加样式
                        var content = suggestion.value;
                        var count = suggestion.count;
                        var html = '<div style="color: #e4b9b9">' + '<div>' + content + '</div>' + '<div style="margin-left: 20px">' + '相关信息' + count + '' + '</div>' + '</div>';
                        return html
                    }
                })
            });
        </script>
    
    </head>
    <body>
    <form id="form1" target="_blank">
    
        <p>姓名:<input type="text" name="user"></p>
    
    </form>
    </body>
    </html>
    模板
    from django.shortcuts import render,HttpResponse
    from app01 import models
    import json
    
    def test(request):
    
        return render(request,'test01.html')
    
    def SearchHistory(request):
        query=request.GET.get('q') #获取用户输入的内容
        #根据用户输入,响应不同的提示
        # ret={"suggestions": ["张根","善良","帅哥"]}
        ret= { "suggestions": [{"value":"张根","data":"...","count":100},{"value":"善良","data":"...","count":1000},{"value":"帅哥","data":"...","count":100}]}
        return HttpResponse(json.dumps(ret,ensure_ascii=False))
    view.py
    from django.conf.urls import url
    from django.contrib import admin
    from app01 import views
    urlpatterns = [
        url(r'^test/$',views.test),
        url(r'^SearchHistory/$',views.SearchHistory),
    ]
    urls.py
     2、其他方法   
            使用下面这些方法只需作为参数传给autocomplete方法即可!
            setOptions(options):  可以在任何时候更改配置的选项
                $('#autocomplete').autocomplete('setOptions',{minChars:1});
            clear: 清除信息提示的缓存以及当前的信息提示
                $('#autocomplete').autocomplete('clear');
            clearCache: 清除信息提示的缓存.
            disable: 禁用自动完成
            enable: 启用自动完成
            hide: 隐藏自动完成
            dispose: 销毁自动完成(移除相关事件以及相关元素)
                $('#autocomplete').autocomplete('dispose');
        3、修改CSS样式 
            .autocomplete-suggestions { border: 1px solid #999; background: #FFF; overflow: auto; }
            .autocomplete-suggestion { padding: 2px 5px; white-space: nowrap; overflow: hidden; }
            .autocomplete-selected { background: #F0F0F0; }
            .autocomplete-suggestions strong { font-weight: normal; color: #3399FF; }
            .autocomplete-group { padding: 2px 5px; }
            .autocomplete-group strong { display: block; border-bottom: 1px solid #000; }
    修改提示框CSS样式

    4.图片灯箱插件

    4.1莫泰对话框形式放大

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <script src="/static/jquery-3.2.1.min.js"></script>
        <script src="/static/plugin/lightbox-2.7.1/lightbox/js/lightbox.min.js"></script>
        <link rel="stylesheet" href="/static/plugin/lightbox-2.7.1/lightbox/css/lightbox.css">
    </head>
    <!--使用情景1 单张图片莫泰框放大  -->
    <a href="/static/plugin/lightbox-2.7.1/lightbox/img/demopage/image-1.jpg" data-lightbox="img1"
       data-title="这是图片1">图片1</a>
    
    <!--使用情景2 多张图片 点击轮播 设置data-lightbox="categroy"  -->
    <a href="/static/plugin/lightbox-2.7.1/lightbox/img/demopage/image-1.jpg" data-lightbox="categroy" data-title="这是图片1"><img
            src="/static/plugin/lightbox-2.7.1/lightbox/img/demopage/thumb-1.jpg" alt=""></a>
    <a href="/static/plugin/lightbox-2.7.1/lightbox/img/demopage/image-2.jpg" data-lightbox="categroy" data-title="这是图片2"><img
            src="/static/plugin/lightbox-2.7.1/lightbox/img/demopage/thumb-2.jpg" alt=""></a>
    <a href="/static/plugin/lightbox-2.7.1/lightbox/img/demopage/image-3.jpg" data-lightbox="categroy" data-title="这是图片3"><img
            src="/static/plugin/lightbox-2.7.1/lightbox/img/demopage/thumb-3.jpg" alt=""></a>
    <a href="/static/plugin/lightbox-2.7.1/lightbox/img/demopage/image-4.jpg" data-lightbox="categroy" data-title="这是图片4"><img
            src="/static/plugin/lightbox-2.7.1/lightbox/img/demopage/thumb-4.jpg" alt=""></a>
    
    <a href="/static/plugin/lightbox-2.7.1/lightbox/img/demopage/image-5.jpg" data-lightbox="categroy" data-title="这是图片2"><img
            src="/static/plugin/lightbox-2.7.1/lightbox/img/demopage/thumb-5.jpg" alt=""></a>
    <a href="/static/plugin/lightbox-2.7.1/lightbox/img/demopage/image-6.jpg" data-lightbox="categroy" data-title="这是图片2"><img
            src="/static/plugin/lightbox-2.7.1/lightbox/img/demopage/thumb-6.jpg" alt=""></a>
    <body>
    
    </body>
    </html>
    模板
    局部修改,增加用户体验
                将:return"Image "+a+" of "+b
                修改为:return a+"/"+b
    修改样式 x/n

    4.2:图片放大镜

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <script src="/static/jquery-3.2.1.min.js"></script>
        <script src="/static/plugin/jqzoom/js/jquery.jqzoom-core.js"></script>
        <link rel="stylesheet" href="/static/plugin/jqzoom/css/jquery.jqzoom.css">
        <script type="text/javascript">
            $(function () {
                $('.jqzoom').jqzoom({
                    zoomType: 'reverse',
                    zoomWidth:300,//放大窗口的宽度
                    zoomHeight:300,//放大窗口的高度
                    xOffset: 10,//放大窗口相对于原图的x轴偏移值,可以为负
                    yOffset:200,//放大窗口相对于原图的y轴偏移值,可以为负
                    position:'right',//放大窗口相对原图的 方位;默认值:'right',还可以是: ,'left' ,'top' ,'bottom'
    {#                lens:false  //设置原图上的显示镜头#}
    
    
                });
            });
        </script>
    </head>
    <body>
    <a href="/static/666.jpg"  class="jqzoom"><img src="/static/666.jpg"  title="青虚山"  ></a>
    
    </body>
    </html>
    图片放大器

    5.jQuery模态对话框插件(Zebra_Dialog)

    Zebra_Dialog是一款简单实用的jQuery模态对话框插件。用它可以替代原生JavaScript的警告框和确认框,也可以用它来制作消息提示框。它兼容IE6+浏览器,支持Ajax加载内容和iFrame框架等。Zebra_Dialog的特点还有: 

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <script src="/static/jquery-3.2.1.min.js"></script>
        <script src="/static/plugin/Zebra_Dialog-master/public/javascript/zebra_dialog.js"></script>
        <link rel="stylesheet" href="/static/plugin/Zebra_Dialog-master/public/css/flat/zebra_dialog.css">
        <script>
            $(function () {
                var dialog1 = null;
                $('button').click(function () {
                    dialog1 = $.Zebra_Dialog({
                        title: '删除评论',//对话框标题
                        message: '确定要删除该评论吗?',//对话框内容
                         400,                       //对话框宽度
                        max_height: 400,                 //对话框高度
                        {#              modal:false,                    //是否显示遮罩层,默认为true#}
                        {#              overlay_close:false,          //设置点击遮罩层是否关闭对话框?默认true#}
                        {#              show_close_button:false,    //设置对话框 是否显示 X 按钮,默认true显示#}
                        type: 'question',       //   设置对话框的类型:'confirmation' 'error''information''question''warning' false,默认:'information'
                        buttons: [
                            {
                                caption: '确定', callback: function (model) {
                                alert('已删除');
                                return true;
                            }
                            },//回调函数内,return表示关闭,return false表示点击时不关闭窗口
                            {
                                caption: '取消', callback: function (model) {
                            }
                            }
                        ],
                        {#                     onClose:function () {          //对话框关闭时执行的回调函数#}
                        {#                        alert('对话框关闭了')#}
                        {#                    },#}
                        /*
                                    source:{                               //通过ajax 引入服务端响应的数据
                                        ajax:{
                                            url:'/SearchHistory/',
                                            cache:false
                                        }
                                    },
                                     source:{
                                        iframe:{
                                            src: 'http://www.le.com',
                                            1000,
                                            height:320
                                        }
                                    },
    
    
    
    
                        source: {inline: $('#myelement')},  //把本地标签引入到莫泰对话框中
                      */
    
    
                        overlay_opacity: 0.1,           //调整遮罩的不透明度(在0和1之间) 默认:0.9
    
                        center_buttons: true,//按钮在对话框的位置
                        custom_class: 'zhanggen',//给对话框添加一个class类名
                        {#                    position:['left-10','top-10'], // 设置对话框在窗口的位置  left,center,right,top,middle,bottom#}
                        animation_speed_show: 2500,//打开对话框需要得时间(毫秒)
                        animation_speed_hide: 1000//关闭对话框所需时间(毫秒)
    
                    });
    
                });
                setTimeout(function () {
                    dialog1.close();
                }, 3000);//公共方法 return结果.close()
            })
        </script>
    </head>
    <body>
    <button>点我</button>
    
    
    <form action="" id="myelement">
        <p>姓名:<input type="text"></p>
        <p><input type="submit" value="提交"></p>
    </form>
    </body>
    </html>
    使用

    6.js-cookie插件

    js-cookie是一个简单的处理Cookie的轻量级JavaScript API,它不是jQuery插件,只是将原来复杂的cookie操作封装起来方便我们使用;

      1、Cookie 设置    
            1)expires:设置cookie生命周期   (单位:天)
                     Cookies.set('name','value',{ expires: 30 });
            2)path:设置cookie的有效web路径,默认/
                     Cookies.set('name', 'value', { path: '' });
            3)domain:定义cookie有效域名,默认当前域
                     Cookies.set('name', 'value',{ domain: 'www.sifangku.com' });
            4)secure:cookie的传输是否需要一个安全协议(HTTPS)

    7.图片剪裁插件(jcrop)

    Jcrop 是一个功能强大的 jQuery 图像裁剪插件,结合后端程序(例如:PHP)可以快速的实现图片裁剪的功能。

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <script src="/static/plugin/tapmodo-Jcrop-1902fbc/js/jquery.min.js"></script>
        <script src="/static/plugin/tapmodo-Jcrop-1902fbc/js/jquery.Jcrop.min.js"></script>
        <link rel="stylesheet" href="/static/plugin/tapmodo-Jcrop-1902fbc/css/jquery.Jcrop.min.css">
        <script>
            $(function () {
                var jcrop_api;
                $('#img1').Jcrop({
                        {#            aspectRatio:2/1,//裁剪区域的 长宽比例:w/h#}
                        {#            minSize:[40,40],//裁剪区域的 最小长、宽#}
                        {#            maxSize:[40,40], //裁剪区域的 最大长、宽#}
                        {#            setSelect:[0,0,200,200] //设置默认选中区域#}
                        {#            bgColor:'#fff',//设置未选中区域的背景颜色#}
                        {#            bgOpacity:0.1 //设置不透明度#}
                        {#            boxWidth:400,//设置图片的大小#}
                        {#            keySupport:false//设置关闭键盘 上下左右键调试,默认开启#}
                        onSelect: function (p) { //当裁剪完成时执行
                            console.log(p)        //裁剪的位置信息,可以发送到服务器端处理
                        },
                        onChange: function (p) { //正在裁剪时执行
    
                        },
                        onRelease: function () {//裁剪取消是执行
    
                        }
                    }
                    , function () {
                        jcrop_api = this;
                    });
                $('button.setSelect').click(function () {
                    jcrop_api.setSelect([100, 100, 300, 300]);
                });
                $('button.animateTo').click(function () {
                    jcrop_api.animateTo([0, 0, 200, 200]);
                });
                $('button.release').click(function () {
                    jcrop_api.release();
                });
                $('button.tellSelect').click(function () {
                    console.log(jcrop_api.tellSelect());
                });
                $('button.tellScaled').click(function () {
                    console.log(jcrop_api.tellScaled());
                });
                $('button.disable').click(function () {
                    jcrop_api.disable();
                });
                $('button.enable').click(function () {
                    jcrop_api.enable();
                });
                $('button.destroy').click(function () {
                    jcrop_api.destroy();
                });
            });
        </script>
    </head>
    <body>
    <img src="/static/666.jpg" alt="" id="img1">
    <button class="setSelect">setSelect</button>
    <button class="animateTo">animateTo</button>
    <button class="release">release</button>
    <button class="tellSelect">tellSelect</button>
    <button class="tellScaled">tellScaled</button>
    <button class="disable">disable</button>
    <button class="enable">enable</button>
    <button class="destroy">destroy</button>
    </body>
    </html>
    应用

    8.右击菜单展示插件

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <script src="/static/jquery-3.2.1.min.js"></script>
        <script src="/static/plugin/contextMenu/jquery.contextMenu.js"></script>
        <link rel="stylesheet" href="/static/plugin/contextMenu/jquery.contextMenu.css">
        <script>
            $(function () {
                $.contextMenu({
                    selector: '.context-menu-one',//给哪个元素,设置鼠标右击 展示菜单的效果
                    items: {
                        "edit": {name: "编辑", icon: "edit"}, //name:菜单显示文字,icon:使用图标
                        "cut": {name: "剪切", icon: "cut"},
                        "copy": {name: "复制", icon: "copy"},
                        "paste": {name: "粘贴", icon: "paste"},
                        "delete": {name: "删除", icon: "delete"},
                        "sep1": "---------",
                        "quit": {name: "取消", icon: "quit"},
                         "zhanggen": {name:"自定义", icon: "quit"} //新增菜单功能,追加jquery.contextMenu.css 92行
                    },
                    callback: function (key, options) {
                        //console.log(key);  //配置的key
                        //console.log(options); //selector:配置元素
    
                    }
                });
            })
        </script>
    </head>
    <body>
    <div class="context-menu-one" style="100px;height:30px;background:pink;">右击我展示菜单</div>
    </body>
    </html>
    基本使用
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <script src="/static/jquery-3.2.1.min.js"></script>
        <script src="/static/plugin/contextMenu/jquery.contextMenu.js"></script>
        <link rel="stylesheet" href="/static/plugin/contextMenu/jquery.contextMenu.css">
        <script>
            $(function () {
                //通过DOM元素上调用contextMenu方法
                $('ul.test').contextMenu({
                    selector: 'li',
                    callback: function (key, options) {
                        console.log(key);
                    },
                    items: {
                        "edit": {name: "编辑", icon: "edit"},
                        "cut": {name: "剪切", icon: "cut"},
                        "copy": {name: "复制", icon: "copy"},
                        "paste": {name: "粘贴", icon: "paste"},
                        "delete": {name: "删除", icon: "delete"},
                        "sep1": "---------",
                        "quit": {name: "取消", icon: "quit"}
                    }
                });
            })
        </script>
    </head>
    <body>
    <ul class="test">
        <li>1</li>
        <li>2</li>
    </ul>
    </body>
    </html>
    通过DOM元素上调用contextMenu方法
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <script src="/static/jquery-3.2.1.min.js"></script>
        <script src="/static/plugin/contextMenu/jquery.contextMenu.js"></script>
        <link rel="stylesheet" href="/static/plugin/contextMenu/jquery.contextMenu.css">
        <script>
            //设置 不同情况 按需动态显示菜单
            $('ul.test').contextMenu({
                selector: 'li',
                build: function ($trigger, e) {
                    if ($trigger.text() == 1) {
                        return {
                            callback: function (key, options) {
                                console.log(key);
                            },
                            items: {
                                "edit": {name: "编辑", icon: "edit"},
                                "cut": {name: "剪切", icon: "cut"},
                                "copy": {name: "复制", icon: "copy"},
                                "paste": {name: "粘贴", icon: "paste"},
                                "delete": {name: "删除", icon: "delete"},
                                "sep1": "---------",
                                "quit": {name: "取消", icon: "quit"}
                            }
                        };
    
                    }
                      if ($trigger.text() == 2) {
                        return {
                            callback: function (key, options) {
                                console.log(key);
                            },
                            items: {
                                "edit": {name: "编辑", icon: "edit"},
                                "cut": {name: "剪切", icon: "cut"},
                                "copy": {name: "复制", icon: "copy"}
                            }
                        };
    
                    }
    
    
                }
            });
        </script>
    </head>
    <body>
    <div class="context-menu-one" style="100px;height:30px;background:pink;">右击我展示菜单</div>
    <ul class="test">
        <li>1</li>
        <li>2</li>
    </ul>
    </body>
    </html>
    设置 不同情况 按需动态显示菜单
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <script src="/static/jquery-3.2.1.min.js"></script>
        <script src="/static/plugin/contextMenu/jquery.contextMenu.js"></script>
        <link rel="stylesheet" href="/static/plugin/contextMenu/jquery.contextMenu.css">
        <script>
            $(function () {
                $.contextMenu({
                    selector: '.context-menu-one',
                    callback: function (key, options) {
                        console.log(key);
                    },
                    items: {
                        "edit": {
                            name: "点击之后关闭",
                            icon: "edit",
                            callback: function () {
                                return true;     //return true 点击之后 展示关闭
                            }
                        },
                        "cut": {
                            name: "点击之后依然显示",
                            icon: "cut",
                            callback: function () {
                                return false;  //return false 点击之后 展示不关闭(可做二级菜单)
                            }
                        }
                    }
                });
            })
        </script>
    </head>
    <body>
    <div class="context-menu-one" style="100px;height:30px;background:pink;">右击我展示菜单</div>
    </body>
    </html>
    设置点击之后不关闭
        $.contextMenu({
            selector: '.context-menu-one', 
            callback: function(key, options) {
                 console.log(key); 
            },
            items: {
                 "edit": {
                      name: "点击之后关闭", 
                      icon: "edit", 
                      callback: function(){ return true; }
                 },
                 "cut": {
                      name: "点击之后依然显示", 
                      icon: "cut", 
                      callback: function(){ return false; }
                 }
            },
            trigger:'none'
        });
    设置手动触发显示
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <script src="/static/jquery-3.2.1.min.js"></script>
        <script src="/static/plugin/contextMenu/jquery.contextMenu.js"></script>
        <link rel="stylesheet" href="/static/plugin/contextMenu/jquery.contextMenu.css">
        <script>
            $(function () {
                $.contextMenu({
                    selector: '.context-menu-one',
                    callback: function (key, options) {
                        var m = "clicked: " + key;
                        console.log(m);
                    },
                    items: {
                        "edit": {"name": "Edit", "icon": "edit"},
                        "cut": {"name": "Cut", "icon": "cut"},
                        "sep1": "---------",
                        "quit": {"name": "Quit", "icon": "quit"},
                        "sep2": "---------",
                        "fold1": {
                            "name": "Sub group",
                            "items": {
                                "fold1-key1": {"name": "Foo bar"},
                                "fold2": {
                                    "name": "Sub group 2",
                                    "items": {
                                        "fold2-key1": {"name": "alpha"},
                                        "fold2-key2": {"name": "bravo"},
                                        "fold2-key3": {"name": "charlie"}
                                    }
                                },
                                "fold1-key3": {"name": "delta"}
                            }
                        },
                        "fold1a": {
                            "name": "Other group",
                            "items": {
                                "fold1a-key1": {"name": "echo"},
                                "fold1a-key2": {"name": "foxtrot"},
                                "fold1a-key3": {"name": "golf"}
                            }
                        }
                    }
                });
    
            })
        </script>
    </head>
    <body>
    <div class="context-menu-one" style="100px;height:30px;background:pink;">右击我展示菜单</div>
    <button class="b2">手动触发!</button>
    
    </body>
    </html>
    配置子菜单

    9.开关按钮控制前后端状态

     <style type="text/css">
            .chooseBtn {
                display: none;
            }
    
            .choose-label {
                box-shadow: #ccc 0px 0px 0px 1px;
                width: 40px;
                height: 20px;
                display: inline-block;
                border-radius: 20px;
                position: relative;
                background-color: #bdbdbd;
                overflow: hidden;
            }
    
            .choose-label:before {
                content: '';
                position: absolute;
                left: 0;
                width: 20px;
                height: 20px;
                display: inline-block;
                border-radius: 20px;
                background-color: #fff;
                z-index: 20;
                -webkit-transition: all 0.5s;
                transition: all 0.5s;
            }
    
            .chooseBtn:checked + label.choose-label:before {
                left: 20px;
            }
    
            .chooseBtn:checked + label.choose-label {
                background-color: green;
            }
        </style>
    CSS
     {% if row.db_status %}
                            <td>
                                <input type="checkbox" name="sex" id="{{ row.pk }}" class="chooseBtn" checked
                                       onchange="switch_status(this,'{{ row.pk }}')">
                                <label for="{{ row.pk }}" class="choose-label"></label>
                            </td>
    
                            <td>
                                <p class="current">
                                    <button class="btn btn-info btn-sm" onclick="option_db('{{ row.pk }}','getdetails')">预览
                                    </button>
                                    <button class="btn btn-info btn-sm" onclick="option_db('{{ row.pk }}','dboption')">进入
                                    </button>
                                </p>
    
                                <p class="prepare" hidden style="color: red">维护中</p>
                            </td>
    
                        {% else %}
                            <td>
                                <input type="checkbox" name="sex" id="{{ row.pk }}" class="chooseBtn"
                                       onchange="switch_status(this,'{{ row.pk }}')">
                                <label for="{{ row.pk }}" class="choose-label"></label>
                            </td>
    
                            <td>
                                <p class="current" style="color: red">维护中</p>
    
                                <p hidden class="prepare">
                                    <button class="btn btn-info btn-sm" onclick="option_db('{{ row.pk }}','getdetails')">预览
                                    </button>
                                    <button class="btn btn-info btn-sm" onclick="option_db('{{ row.pk }}','dboption')">进入
                                    </button>
                                </p>
                            </td>
                        {% endif %}
    HTML
          function switch_status(self, pk) {
                var $current_status = ($(self).prop('checked'));
                var status = 1;
                if ($current_status == false) {status = 0;}
                $(self).parent().next().find('.prepare').toggle('hidden');
                $(self).parent().next().find('.current').toggle('active');
                $.ajax({
                    type: 'get',
                    async: false,
                    cache: false,
                    url: '{% url "instance_list" %}',
                    dataType: 'json',
                    data: {'dbid': pk, 'option': 'togle_status', 'status': status},
                    success: function (data) {
                        alert(data)
                    }
                })
    
            }
    js

    10.Chart.js 

    一款开源的前端图表生成工具

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <script src="/static/jquery-3.2.1.min.js"></script>
    {#    <script src="/static/pligin/jQuery-cokie/jquery.cookie.js"></script>#}
        <link href="/static/bootstrap/css/bootstrap.css" rel="stylesheet">
        <script src="/static/bootstrap/js/bootstrap.js"></script>
    {#    <script src="/static/pligin/jquery-validation-1.14.0/dist/jquery.validate.min.js"></script>#}
    {#    <script src="/static/pligin/jquery-validation-1.14.0/dist/additional-methods.min.js"></script>#}
    {#    <script src="/static/pligin/jquery-validation-1.14.0/dist/localization/messages_zh.min.js"></script>#}
        <!-- bootstarp相关结束-->
    </head>
    <body>
    <!-- cards -->
    <div class="row cards">
    
        <div class="card-container col-lg-3 col-sm-6 col-sm-12">
            <div class="card card-blue hover">
                <div class="front">
    
                    <div class="media">
                          <span class="pull-left">
                            <i class="fa fa-users media-object"></i>
                          </span>
    
                        <div class="media-body">
                            <small>Hosts</small>
                            <h2 class="media-heading animate-number" data-value="100"
                                data-animation-duration="1500">0</h2>
                        </div>
                    </div>
    
                </div>
                <div class="back">
                    <a href="">
                        <i class="fa fa-bar-chart-o fa-4x"></i>
                        <span>Check Summary</span>
                    </a>
                </div>
            </div>
        </div>
    
    
        <div class="card-container col-lg-3 col-sm-6 col-sm-12">
            <div class="card card-redbrown hover">
                <div class="front">
    
                    <div class="media">
                          <span class="pull-left">
                            <i class="fa fa-book media-object"></i>
                          </span>
    
                        <div class="media-body">
                            <small>Problem Host</small>
                            <h2 class="media-heading animate-number" data-value="100"
                                data-animation-duration="1500">0</h2>
                        </div>
                    </div>
    
    
                </div>
                <div class="back">
                    <a href="">
                        <i class="fa fa-bar-chart-o fa-4x"></i>
                        <span>Check Summary</span>
                    </a>
                </div>
            </div>
        </div>
    
    
        <div class="card-container col-lg-3 col-sm-6 col-sm-12">
            <div class="card card-greensea hover">
                <div class="front">
    
                    <div class="media">
                          <span class="pull-left">
                            <i class="fa fa-map media-object"></i>
                          </span>
    
                        <div class="media-body">
                            <small>Work Order</small>
                            <h2 class="media-heading animate-number" data-value="300"
                                data-animation-duration="1500">0</h2>
                        </div>
                    </div>
    
                </div>
                <div class="back">
                    <a href="">
                        <i class="fa fa-bar-chart-o fa-4x"></i>
                        <span>Check Summary</span>
                    </a>
                </div>
            </div>
        </div>
    
    
        <div class="card-container col-lg-3 col-sm-6 col-xs-12">
            <div class="card card-slategray hover">
                <div class="front">
    
                    <div class="media">
                          <span class="pull-left">
                            <i class="fa fa-eye media-object"></i>
                          </span>
    
                        <div class="media-body">
                            <small>Pending Work Order</small>
                            <h2 class="media-heading animate-number" data-value="200"
                                data-animation-duration="1500">0</h2>
                        </div>
                    </div>
    
                </div>
                <div class="back">
                    <a href="">
                        <i class="fa fa-bar-chart-o fa-4x"></i>
                        <span>Check Summary</span>
                    </a>
                </div>
            </div>
        </div>
    
    
    </div>
    
    <div class="row">
    
    
        <div class="col-lg-6 col-sm-6 col-sm-12">
            <!-- tile header -->
            <div class="tile-header">
                <h1 class="filled orange"><strong>主机</strong>状态</h1>
                <div class="controls">
                    <a href="#" class="refresh"><i class="fa fa-refresh"></i></a>
                    <a href="#" class="remove"><i class="fa fa-times"></i></a>
                </div>
            </div>
            <!-- /tile header -->
            <!-- tile body -->
            <div class="tile-body nopadding">
                <canvas class="filled " id="myChart"></canvas>
            </div>
        </div>
    
        <div class="col-lg-6 col-sm-6 col-sm-12">
            <!-- tile header -->
            <div class="tile-header">
                <h1 class=" filled greensea"><strong>工单</strong>状态</h1>
                <div class="controls">
                    <a href="#" class="refresh"><i class="fa fa-refresh"></i></a>
                    <a href="#" class="remove"><i class="fa fa-times"></i></a>
                </div>
            </div>
            <!-- /tile header -->
            <!-- tile body -->
            <div class="tile-body nopadding">
                <canvas class="filled" id="myChart1"></canvas>
            </div>
        </div>
    
    
    </div>
    </body>
    <script src="/static/node_modules/chart.js/dist/Chart.js"></script>
    <script>
        function beforePrintHandler() {
            for (var id in Chart.instances) {
                Chart.instances[id].resize()
            }
        }
    
        var ctx = document.getElementById('myChart').getContext('2d');
        var chart = new Chart(ctx, {
            // 要创建的图表类型
            type: 'pie',
    
            // 数据集
            data: {
                labels: ["存活", "离线", "问题"],
                datasets: [{
                    label: "Server status",
                    backgroundColor: ['rgb(46,139,87)', 'rgb(165,42,42)', 'rgb(205,205,0)'],
                    data: [100 - 200,300]
    
                }]
            },
    
            // 配置项
            options: {}
        });
        var ctx1 = document.getElementById('myChart1').getContext('2d');
    
        var myBarChart = new Chart(ctx1, {
            type: 'pie',
            data: {
                labels: ["已处理", "待处理", "已超时"],
                datasets: [{
                    label: "Work order usage",
                    backgroundColor: ['rgb(46,139,87)', 'rgb(255,255,0)', 'rgb(0,0,255)'],
                    data: [100 -200,300, 0]
                }]
            },
            options: {}
        });
        var ctx2 = document.getElementById('myChart2').getContext('2d');
    
        var myRadarChart = new Chart(ctx2, {
            type: 'radar',
            data: {
                labels: ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"],
                datasets: [{
                    label: "Work order usage",
                    backgroundColor: 'rgb(255, 99, 132)',
                    borderColor: 'rgb(255, 99, 132)',
                    data: [1, 3, 5, 2, 13, 9, 7]
                }]
            },
            options: {}
        });
        var ctx3 = document.getElementById('myChart3').getContext('2d');
    
        var myPieChart = new Chart(ctx3, {
            type: 'pie',
            data: {
                datasets: [{
                    data: [10, 20, 30],
                    backgroundColor: ['rgb(255, 99, 132)', 'rgb(55,99,132)', 'rgb(124,99,132)']
                }],
    
                labels: [
                    'Red',
                    'Yellow',
                    'Blue'
                ]
            },
            options: {}
        });
    
        var ctx4 = document.getElementById('myChart4').getContext('2d');
        var myDoughnutChart = new Chart(ctx4, {
            type: 'doughnut',
            data: {
                datasets: [{
                    data: [10, 20, 30],
                    backgroundColor: ['rgb(255, 99, 132)', 'rgb(55,99,132)', 'rgb(124,99,132)']
    
                }],
    
                // These labels appear in the legend and in the tooltips when hovering different arcs
                labels: [
                    'Red',
                    'Yellow',
                    'Blue'
                ]
            },
            options: {}
        });
    </script>
    </html>
    实例代码

    11.dataTables.js

    Datatables是一款jquery表格插件。它是一个高度灵活的工具,可以将任何HTML表格添加高级的交互功能。

    • 分页,即时搜索和排序         哈哈哈再也不要写分页插件了
    • 几乎支持任何数据源:DOM, javascript, Ajax 和 服务器处理
    • 支持不同主题 DataTables, jQuery UI, Bootstrap, Foundation
    • 各式各样的扩展: Editor, TableTools, FixedColumns ……
    • 丰富多样的option和强大的API
    • 支持国际化
    • 超过2900+个单元测试
    • 免费开源 ( MIT license )! 商业支持
    • 更多特性请到官网查看
        <script src="{% static 'plugins/datatables/jquery.dataTables.min.js' %}"></script>
        <script src="{% static 'plugins/datatables/dataTables.bootstrap.min.js' %}"></script>
        <script>
            /* Datatables是一款jquery表格插件。它是一个高度灵活的工具,可以将任何HTML表格添加高级的交互功能。 */
            function set_tables() {
                $('#host_table').DataTable({
                    "paging": true, <!-- 允许分页 -->
                    "lengthChange": true, <!-- 允许改变每页显示的行数 -->
                    "searching": true, <!-- 允许内容搜索 -->
                    "ordering": true, <!-- 允许排序 -->
                    "info": true, <!-- 显示信息 -->
                    "autoWidth": true
                });
            }
            set_tables()
        </script>
    使用

    注意:

    使用dataTables.js插件,table标签中必须包含 thead和 tbody标签,而且tr不能仅为1行;

    12.crontable生成插件

    <html>
    <head>
        <title>Cron表达式添加</title>
        <link rel="stylesheet" href="/static/bootstrap/css/bootstrap.css">
        <link href="/static/audit_app/Cron/themes/bootstrap/easyui.min.css" rel="stylesheet" type="text/css"/>
        <link href="/static/audit_app/Cron/themes/icon.css" rel="stylesheet" type="text/css"/>
        <link href="/static/audit_app/Cron/icon.css" rel="stylesheet" type="text/css"/>
        <style type="text/css">
            .line {
                height: 25px;
                line-height: 25px;
                margin: 3px;
            }
    
            .imp {
                padding-left: 25px;
            }
    
            .col {
                width: 95px;
            }
    
            ul {
                list-style: none;
                padding-left: 10px;
            }
    
            li {
                height: 20px;
            }
        </style>
        <script src="/static/audit_app/Cron/jquery-1.6.2.min.js" type="text/javascript"></script>
        <script src="/static/audit_app/Cron/jquery.easyui.min.js" type="text/javascript"></script>
        <script src="/static/audit_app/Cron/cron.js" type="text/javascript"></script>
    <body>
    <a class='btn btn-success' href="/audit/crontab/{{ host_user_bind.pk }}/">返回</a>
    <center>
        <div class="easyui-layout" style="830px;height:560px; border: 1px rgb(202, 196, 196) solid;
                border-radius: 5px;">
            <div style="height: 100%;">
    
                <div class="easyui-tabs" data-options="fit:true,border:false">
    
                    <div title="秒">
                        <div class="line">
                            <input type="radio" checked="checked" name="second" onclick="everyTime(this)">
                            每秒 允许的通配符[, - * /]
                        </div>
                        <div class="line">
                            <input type="radio" name="second" onclick="cycle(this)">
                            周期从
                            <input class="numberspinner" style=" 60px;" data-options="min:1,max:58" value="1"
                                   id="secondStart_0">
                            -
                            <input class="numberspinner" style=" 60px;" data-options="min:2,max:59" value="2"
                                   id="secondEnd_0"></div>
                        <div class="line">
                            <input type="radio" name="second" onclick="startOn(this)"><input class="numberspinner" style=" 60px;" data-options="min:0,max:59" value="0"
                                   id="secondStart_1">
                            秒开始,每
                            <input class="numberspinner" style=" 60px;" data-options="min:1,max:59" value="1"
                                   id="secondEnd_1">
                            秒执行一次
                        </div>
                        <div class="line">
                            <input type="radio" name="second" id="sencond_appoint">
                            指定
                        </div>
                        <div class="imp secondList">
                            <input type="checkbox" value="0">00
                            <input type="checkbox" value="1">01
                            <input type="checkbox" value="2">02
                            <input type="checkbox" value="3">03
                            <input type="checkbox" value="4">04
                            <input type="checkbox" value="5">05
                            <input type="checkbox" value="6">06
                            <input type="checkbox" value="7">07
                            <input type="checkbox" value="8">08
                            <input type="checkbox" value="9">09
                        </div>
                        <div class="imp secondList">
                            <input type="checkbox" value="10">10
                            <input type="checkbox" value="11">11
                            <input type="checkbox" value="12">12
                            <input type="checkbox" value="13">13
                            <input type="checkbox" value="14">14
                            <input type="checkbox" value="15">15
                            <input type="checkbox" value="16">16
                            <input type="checkbox" value="17">17
                            <input type="checkbox" value="18">18
                            <input type="checkbox" value="19">19
                        </div>
                        <div class="imp secondList">
                            <input type="checkbox" value="20">20
                            <input type="checkbox" value="21">21
                            <input type="checkbox" value="22">22
                            <input type="checkbox" value="23">23
                            <input type="checkbox" value="24">24
                            <input type="checkbox" value="25">25
                            <input type="checkbox" value="26">26
                            <input type="checkbox" value="27">27
                            <input type="checkbox" value="28">28
                            <input type="checkbox" value="29">29
                        </div>
                        <div class="imp secondList">
                            <input type="checkbox" value="30">30
                            <input type="checkbox" value="31">31
                            <input type="checkbox" value="32">32
                            <input type="checkbox" value="33">33
                            <input type="checkbox" value="34">34
                            <input type="checkbox" value="35">35
                            <input type="checkbox" value="36">36
                            <input type="checkbox" value="37">37
                            <input type="checkbox" value="38">38
                            <input type="checkbox" value="39">39
                        </div>
                        <div class="imp secondList">
                            <input type="checkbox" value="40">40
                            <input type="checkbox" value="41">41
                            <input type="checkbox" value="42">42
                            <input type="checkbox" value="43">43
                            <input type="checkbox" value="44">44
                            <input type="checkbox" value="45">45
                            <input type="checkbox" value="46">46
                            <input type="checkbox" value="47">47
                            <input type="checkbox" value="48">48
                            <input type="checkbox" value="49">49
                        </div>
                        <div class="imp secondList">
                            <input type="checkbox" value="50">50
                            <input type="checkbox" value="51">51
                            <input type="checkbox" value="52">52
                            <input type="checkbox" value="53">53
                            <input type="checkbox" value="54">54
                            <input type="checkbox" value="55">55
                            <input type="checkbox" value="56">56
                            <input type="checkbox" value="57">57
                            <input type="checkbox" value="58">58
                            <input type="checkbox" value="59">59
                        </div>
                    </div>
                    <div title="分钟">
                        <div class="line">
                            <input type="radio" checked="checked" name="min" onclick="everyTime(this)">
                            分钟 允许的通配符[, - * /]
                        </div>
                        <div class="line">
                            <input type="radio" name="min" onclick="cycle(this)">
                            周期从
                            <input class="numberspinner" style=" 60px;" data-options="min:1,max:58" value="1"
                                   id="minStart_0">
                            -
                            <input class="numberspinner" style=" 60px;" data-options="min:2,max:59" value="2"
                                   id="minEnd_0">
                            分钟
                        </div>
                        <div class="line">
                            <input type="radio" name="min" onclick="startOn(this)"><input class="numberspinner" style=" 60px;" data-options="min:0,max:59" value="0"
                                   id="minStart_1">
                            分钟开始,每
                            <input class="numberspinner" style=" 60px;" data-options="min:1,max:59" value="1"
                                   id="minEnd_1">
                            分钟执行一次
                        </div>
                        <div class="line">
                            <input type="radio" name="min" id="min_appoint">
                            指定
                        </div>
                        <div class="imp minList">
                            <input type="checkbox" value="0">00
                            <input type="checkbox" value="1">01
                            <input type="checkbox" value="2">02
                            <input type="checkbox" value="3">03
                            <input type="checkbox" value="4">04
                            <input type="checkbox" value="5">05
                            <input type="checkbox" value="6">06
                            <input type="checkbox" value="7">07
                            <input type="checkbox" value="8">08
                            <input type="checkbox" value="9">09
                        </div>
                        <div class="imp minList">
                            <input type="checkbox" value="10">10
                            <input type="checkbox" value="11">11
                            <input type="checkbox" value="12">12
                            <input type="checkbox" value="13">13
                            <input type="checkbox" value="14">14
                            <input type="checkbox" value="15">15
                            <input type="checkbox" value="16">16
                            <input type="checkbox" value="17">17
                            <input type="checkbox" value="18">18
                            <input type="checkbox" value="19">19
                        </div>
                        <div class="imp minList">
                            <input type="checkbox" value="20">20
                            <input type="checkbox" value="21">21
                            <input type="checkbox" value="22">22
                            <input type="checkbox" value="23">23
                            <input type="checkbox" value="24">24
                            <input type="checkbox" value="25">25
                            <input type="checkbox" value="26">26
                            <input type="checkbox" value="27">27
                            <input type="checkbox" value="28">28
                            <input type="checkbox" value="29">29
                        </div>
                        <div class="imp minList">
                            <input type="checkbox" value="30">30
                            <input type="checkbox" value="31">31
                            <input type="checkbox" value="32">32
                            <input type="checkbox" value="33">33
                            <input type="checkbox" value="34">34
                            <input type="checkbox" value="35">35
                            <input type="checkbox" value="36">36
                            <input type="checkbox" value="37">37
                            <input type="checkbox" value="38">38
                            <input type="checkbox" value="39">39
                        </div>
                        <div class="imp minList">
                            <input type="checkbox" value="40">40
                            <input type="checkbox" value="41">41
                            <input type="checkbox" value="42">42
                            <input type="checkbox" value="43">43
                            <input type="checkbox" value="44">44
                            <input type="checkbox" value="45">45
                            <input type="checkbox" value="46">46
                            <input type="checkbox" value="47">47
                            <input type="checkbox" value="48">48
                            <input type="checkbox" value="49">49
                        </div>
                        <div class="imp minList">
                            <input type="checkbox" value="50">50
                            <input type="checkbox" value="51">51
                            <input type="checkbox" value="52">52
                            <input type="checkbox" value="53">53
                            <input type="checkbox" value="54">54
                            <input type="checkbox" value="55">55
                            <input type="checkbox" value="56">56
                            <input type="checkbox" value="57">57
                            <input type="checkbox" value="58">58
                            <input type="checkbox" value="59">59
                        </div>
                    </div>
                    <div title="小时">
                        <div class="line">
                            <input type="radio" checked="checked" name="hour" onclick="everyTime(this)">
                            小时 允许的通配符[, - * /]
                        </div>
                        <div class="line">
                            <input type="radio" name="hour" onclick="cycle(this)">
                            周期从
                            <input class="numberspinner" style=" 60px;" data-options="min:0,max:23" value="0"
                                   id="hourStart_0">
                            -
                            <input class="numberspinner" style=" 60px;" data-options="min:2,max:23" value="2"
                                   id="hourEnd_1">
                            小时
                        </div>
                        <div class="line">
                            <input type="radio" name="hour" onclick="startOn(this)"><input class="numberspinner" style=" 60px;" data-options="min:0,max:23" value="0"
                                   id="hourStart_1">
                            小时开始,每
                            <input class="numberspinner" style=" 60px;" data-options="min:1,max:23" value="1"
                                   id="hourEnd_1">
                            小时执行一次
                        </div>
                        <div class="line">
                            <input type="radio" name="hour" id="hour_appoint">
                            指定
                        </div>
                        <div class="imp hourList">
                            AM:
                            <input type="checkbox" value="0">00
                            <input type="checkbox" value="1">01
                            <input type="checkbox" value="2">02
                            <input type="checkbox" value="3">03
                            <input type="checkbox" value="4">04
                            <input type="checkbox" value="5">05
                            <input type="checkbox" value="6">06
                            <input type="checkbox" value="7">07
                            <input type="checkbox" value="8">08
                            <input type="checkbox" value="9">09
                            <input type="checkbox" value="10">10
                            <input type="checkbox" value="11">11
                        </div>
                        <div class="imp hourList">
                            PM:
                            <input type="checkbox" value="12">12
                            <input type="checkbox" value="13">13
                            <input type="checkbox" value="14">14
                            <input type="checkbox" value="15">15
                            <input type="checkbox" value="16">16
                            <input type="checkbox" value="17">17
                            <input type="checkbox" value="18">18
                            <input type="checkbox" value="19">19
                            <input type="checkbox" value="20">20
                            <input type="checkbox" value="21">21
                            <input type="checkbox" value="22">22
                            <input type="checkbox" value="23">23
                        </div>
                    </div>
                    <div title="日">
                        <div class="line">
                            <input type="radio" checked="checked" name="day" onclick="everyTime(this)">
                            日 允许的通配符[, - * / L W]
                        </div>
                        <div class="line">
                            <input type="radio" name="day" onclick="unAppoint(this)">
                            不指定
                        </div>
                        <div class="line">
                            <input type="radio" name="day" onclick="cycle(this)">
                            周期从
                            <input class="numberspinner" style=" 60px;" data-options="min:1,max:31" value="1"
                                   id="dayStart_0">
                            -
                            <input class="numberspinner" style=" 60px;" data-options="min:2,max:31" value="2"
                                   id="dayEnd_0"></div>
                        <div class="line">
                            <input type="radio" name="day" onclick="startOn(this)"><input class="numberspinner" style=" 60px;" data-options="min:1,max:31" value="1"
                                   id="dayStart_1">
                            日开始,每
                            <input class="numberspinner" style=" 60px;" data-options="min:1,max:31" value="1"
                                   id="dayEnd_1">
                            天执行一次
                        </div>
                        <div class="line">
                            <input type="radio" name="day" onclick="workDay(this)">
                            每月
                            <input class="numberspinner" style=" 60px;" data-options="min:1,max:31" value="1"
                                   id="dayStart_2">
                            号最近的那个工作日
                        </div>
                        <div class="line">
                            <input type="radio" name="day" onclick="lastDay(this)">
                            本月最后一天
                        </div>
                        <div class="line">
                            <input type="radio" name="day" id="day_appoint">
                            指定
                        </div>
                        <div class="imp dayList">
                            <input type="checkbox" value="1">1
                            <input type="checkbox" value="2">2
                            <input type="checkbox" value="3">3
                            <input type="checkbox" value="4">4
                            <input type="checkbox" value="5">5
                            <input type="checkbox" value="6">6
                            <input type="checkbox" value="7">7
                            <input type="checkbox" value="8">8
                            <input type="checkbox" value="9">9
                            <input type="checkbox" value="10">10
                            <input type="checkbox" value="11">11
                            <input type="checkbox" value="12">12
                            <input type="checkbox" value="13">13
                            <input type="checkbox" value="14">14
                            <input type="checkbox" value="15">15
                            <input type="checkbox" value="16">16
                        </div>
                        <div class="imp dayList">
                            <input type="checkbox" value="17">17
                            <input type="checkbox" value="18">18
                            <input type="checkbox" value="19">19
                            <input type="checkbox" value="20">20
                            <input type="checkbox" value="21">21
                            <input type="checkbox" value="22">22
                            <input type="checkbox" value="23">23
                            <input type="checkbox" value="24">24
                            <input type="checkbox" value="25">25
                            <input type="checkbox" value="26">26
                            <input type="checkbox" value="27">27
                            <input type="checkbox" value="28">28
                            <input type="checkbox" value="29">29
                            <input type="checkbox" value="30">30
                            <input type="checkbox" value="31">31
                        </div>
                    </div>
                    <div title="月">
                        <div class="line">
                            <input type="radio" checked="checked" name="mouth" onclick="everyTime(this)">
                            月 允许的通配符[, - * /]
                        </div>
                        <div class="line">
                            <input type="radio" name="mouth" onclick="unAppoint(this)">
                            不指定
                        </div>
                        <div class="line">
                            <input type="radio" name="mouth" onclick="cycle(this)">
                            周期从
                            <input class="numberspinner" style=" 60px;" data-options="min:1,max:12" value="1"
                                   id="mouthStart_0">
                            -
                            <input class="numberspinner" style=" 60px;" data-options="min:2,max:12" value="2"
                                   id="mouthEnd_0"></div>
                        <div class="line">
                            <input type="radio" name="mouth" onclick="startOn(this)"><input class="numberspinner" style=" 60px;" data-options="min:1,max:12" value="1"
                                   id="mouthStart_1">
                            日开始,每
                            <input class="numberspinner" style=" 60px;" data-options="min:1,max:12" value="1"
                                   id="mouthEnd_1">
                            月执行一次
                        </div>
                        <div class="line">
                            <input type="radio" name="mouth" id="mouth_appoint">
                            指定
                        </div>
                        <div class="imp mouthList">
                            <input type="checkbox" value="1">1
                            <input type="checkbox" value="2">2
                            <input type="checkbox" value="3">3
                            <input type="checkbox" value="4">4
                            <input type="checkbox" value="5">5
                            <input type="checkbox" value="6">6
                            <input type="checkbox" value="7">7
                            <input type="checkbox" value="8">8
                            <input type="checkbox" value="9">9
                            <input type="checkbox" value="10">10
                            <input type="checkbox" value="11">11
                            <input type="checkbox" value="12">12
                        </div>
                    </div>
                    <div title="周">
                        <div class="line">
                            <input type="radio" checked="checked" name="week" onclick="everyTime(this)">
                            周 允许的通配符[, - * / L #]
                        </div>
                        <div class="line">
                            <input type="radio" name="week" onclick="unAppoint(this)">
                            不指定
                        </div>
                        <div class="line">
                            <input type="radio" name="week" onclick="startOn(this)">
                            周期 从星期<input class="numberspinner" style=" 60px;" data-options="min:1,max:7"
                                         id="weekStart_0" value="1">
                            -
                            <input class="numberspinner" style=" 60px;" data-options="min:2,max:7" value="2"
                                   id="weekEnd_0"></div>
                        <div class="line">
                            <input type="radio" name="week" onclick="weekOfDay(this)"><input class="numberspinner" style=" 60px;" data-options="min:1,max:4" value="1"
                                    id="weekStart_1">
                            周 的星期<input class="numberspinner" style=" 60px;" data-options="min:1,max:7"
                                        id="weekEnd_1" value="1"></div>
                        <div class="line">
                            <input type="radio" name="week" onclick="lastWeek(this)">
                            本月最后一个星期<input class="numberspinner" style=" 60px;" data-options="min:1,max:7"
                                           id="weekStart_2" value="1"></div>
                        <div class="line">
                            <input type="radio" name="week" id="week_appoint">
                            指定
                        </div>
                        <div class="imp weekList">
                            <input type="checkbox" value="1">1
                            <input type="checkbox" value="2">2
                            <input type="checkbox" value="3">3
                            <input type="checkbox" value="4">4
                            <input type="checkbox" value="5">5
                            <input type="checkbox" value="6">6
                            <input type="checkbox" value="7">7
                        </div>
                    </div>
                    <div title="年">
                        <div class="line">
                            <input type="radio" checked="checked" name="year" onclick="unAppoint(this)">
                            不指定 允许的通配符[, - * /] 非必填
                        </div>
                        <div class="line">
                            <input type="radio" name="year" onclick="everyTime(this)">
                            每年
                        </div>
                        <div class="line">
                            <input type="radio" name="year" onclick="cycle(this)">周期 从
                            <input class="numberspinner" style=" 90px;" data-options="min:2013,max:3000"
                                   id="yearStart_0" value="2013">
                            -
                            <input class="numberspinner" style=" 90px;" data-options="min:2014,max:3000"
                                   id="yearEnd_0" value="2014"></div>
                    </div>
                </div>
            </div>
            <div data-options="region:'south',border:false" style="height:250px">
                <fieldset style="border-radius: 3px; height: 220px;">
                    <legend>表达式</legend>
                    <table style="height: 100px;">
                        <tbody>
                        <tr>
                            <td>
                            </td>
                            <td align="center"></td>
                            <td align="center">
                                分钟
                            </td>
                            <td align="center">
                                小时
                            </td>
                            <td align="center"></td>
                            <td align="center"><br/>
                            </td>
                            <td align="center">
                                星期
                            </td>
                            <td align="center"></td>
                        </tr>
                        <tr>
                            <td>
                                表达式字段:
                            </td>
                            <td>
                                <input type="text" name="v_second" class="col" value="*" readonly="readonly"/>
                            </td>
                            <td>
                                <input type="text" name="v_min" class="col" value="*" readonly="readonly"/>
                            </td>
                            <td>
                                <input type="text" name="v_hour" class="col" value="*" readonly="readonly"/>
                            </td>
                            <td>
                                <input type="text" name="v_day" class="col" value="*" readonly="readonly"/>
                            </td>
                            <td>
                                <input type="text" name="v_mouth" class="col" value="*" readonly="readonly"/>
                            </td>
                            <td>
                                <input type="text" name="v_week" class="col" value="?" readonly="readonly"/>
                            </td>
                            <td>
                                <input type="text" name="v_year" class="col" readonly="readonly"/>
                            </td>
                        </tr>
                        <tr>
                            <td>Cron 表达式:</td>
                            <td colspan="6"><input type="text" name="cron" style=" 100%;"
                                                   id="cron"
                            /></td> <!-- value="* * * * * ?"--->
                        </tr>
                         <tr>
                            <td>执行内容:</td>
                            <td colspan="6"><input type="text" name="cron_task"
                                                   style=" 100%;"
                            /></td>
                        </tr>
                        <tr>
                            <td>创建用户:</td>
                            <td colspan="6"><input value="{{ request.session.username }}" type="text" name="cron_user"
                                                   style=" 100%;"
                            /></td>
                        </tr>
                        <tr>
                            <td>说明:</td>
                            <td colspan="6"><input type="text" name="cron_desicrible"
                                                   style=" 100%;"
                            /></td>
                        </tr>
                        </tbody>
                    </table>
                    <button class="btn btn-success col-md-offset-10" onclick="submit_crontable()">提交</button>
                </fieldset>
                <div style="text-align: center; margin-top: 5px;">
                    <script type="text/javascript">
                        /*killIe*/
                        $.parser.parse($("body"));
                        var cpro_id = "u1331261";
    
                        function btnFan() {
                            //获取参数中表达式的值
                            var txt = $("#cron").val();
                            if (txt) {
                                var regs = txt.split(' ');
                                $("input[name=v_second]").val(regs[0]);
                                $("input[name=v_min]").val(regs[1]);
                                $("input[name=v_hour]").val(regs[2]);
                                $("input[name=v_day]").val(regs[3]);
                                $("input[name=v_mouth]").val(regs[4]);
                                $("input[name=v_week]").val(regs[5]);
    
                                initObj(regs[0], "second");
                                initObj(regs[1], "min");
                                initObj(regs[2], "hour");
                                initDay(regs[3]);
                                initMonth(regs[4]);
                                initWeek(regs[5]);
    
                                if (regs.length > 6) {
                                    $("input[name=v_year]").val(regs[6]);
                                    initYear(regs[6]);
                                }
                            }
                        }
    
    
                        function initObj(strVal, strid) {
                            var ary = null;
                            var objRadio = $("input[name='" + strid + "'");
                            if (strVal == "*") {
                                objRadio.eq(0).attr("checked", "checked");
                            } else if (strVal.split('-').length > 1) {
                                ary = strVal.split('-');
                                objRadio.eq(1).attr("checked", "checked");
                                $("#" + strid + "Start_0").numberspinner('setValue', ary[0]);
                                $("#" + strid + "End_0").numberspinner('setValue', ary[1]);
                            } else if (strVal.split('/').length > 1) {
                                ary = strVal.split('/');
                                objRadio.eq(2).attr("checked", "checked");
                                $("#" + strid + "Start_1").numberspinner('setValue', ary[0]);
                                $("#" + strid + "End_1").numberspinner('setValue', ary[1]);
                            } else {
                                objRadio.eq(3).attr("checked", "checked");
                                if (strVal != "?") {
                                    ary = strVal.split(",");
                                    for (var i = 0; i < ary.length; i++) {
                                        $("." + strid + "List input[value='" + ary[i] + "']").attr("checked", "checked");
                                    }
                                }
                            }
                        }
    
                        function initDay(strVal) {
                            var ary = null;
                            var objRadio = $("input[name='day']");
                            if (strVal == "*") {
                                objRadio.eq(0).attr("checked", "checked");
                            } else if (strVal == "?") {
                                objRadio.eq(1).attr("checked", "checked");
                            } else if (strVal.split('-').length > 1) {
                                ary = strVal.split('-');
                                objRadio.eq(2).attr("checked", "checked");
                                $("#dayStart_0").numberspinner('setValue', ary[0]);
                                $("#dayEnd_0").numberspinner('setValue', ary[1]);
                            } else if (strVal.split('/').length > 1) {
                                ary = strVal.split('/');
                                objRadio.eq(3).attr("checked", "checked");
                                $("#dayStart_1").numberspinner('setValue', ary[0]);
                                $("#dayEnd_1").numberspinner('setValue', ary[1]);
                            } else if (strVal.split('W').length > 1) {
                                ary = strVal.split('W');
                                objRadio.eq(4).attr("checked", "checked");
                                $("#dayStart_2").numberspinner('setValue', ary[0]);
                            } else if (strVal == "L") {
                                objRadio.eq(5).attr("checked", "checked");
                            } else {
                                objRadio.eq(6).attr("checked", "checked");
                                ary = strVal.split(",");
                                for (var i = 0; i < ary.length; i++) {
                                    $(".dayList input[value='" + ary[i] + "']").attr("checked", "checked");
                                }
                            }
                        }
    
                        function initMonth(strVal) {
                            var ary = null;
                            var objRadio = $("input[name='mouth']");
                            if (strVal == "*") {
                                objRadio.eq(0).attr("checked", "checked");
                            } else if (strVal == "?") {
                                objRadio.eq(1).attr("checked", "checked");
                            } else if (strVal.split('-').length > 1) {
                                ary = strVal.split('-');
                                objRadio.eq(2).attr("checked", "checked");
                                $("#mouthStart_0").numberspinner('setValue', ary[0]);
                                $("#mouthEnd_0").numberspinner('setValue', ary[1]);
                            } else if (strVal.split('/').length > 1) {
                                ary = strVal.split('/');
                                objRadio.eq(3).attr("checked", "checked");
                                $("#mouthStart_1").numberspinner('setValue', ary[0]);
                                $("#mouthEnd_1").numberspinner('setValue', ary[1]);
    
                            } else {
                                objRadio.eq(4).attr("checked", "checked");
    
                                ary = strVal.split(",");
                                for (var i = 0; i < ary.length; i++) {
                                    $(".mouthList input[value='" + ary[i] + "']").attr("checked", "checked");
                                }
                            }
                        }
    
                        function initWeek(strVal) {
                            var ary = null;
                            var objRadio = $("input[name='week']");
                            if (strVal == "*") {
                                objRadio.eq(0).attr("checked", "checked");
                            } else if (strVal == "?") {
                                objRadio.eq(1).attr("checked", "checked");
                            } else if (strVal.split('/').length > 1) {
                                ary = strVal.split('/');
                                objRadio.eq(2).attr("checked", "checked");
                                $("#weekStart_0").numberspinner('setValue', ary[0]);
                                $("#weekEnd_0").numberspinner('setValue', ary[1]);
                            } else if (strVal.split('-').length > 1) {
                                ary = strVal.split('-');
                                objRadio.eq(3).attr("checked", "checked");
                                $("#weekStart_1").numberspinner('setValue', ary[0]);
                                $("#weekEnd_1").numberspinner('setValue', ary[1]);
                            } else if (strVal.split('L').length > 1) {
                                ary = strVal.split('L');
                                objRadio.eq(4).attr("checked", "checked");
                                $("#weekStart_2").numberspinner('setValue', ary[0]);
                            } else {
                                objRadio.eq(5).attr("checked", "checked");
                                ary = strVal.split(",");
                                for (var i = 0; i < ary.length; i++) {
                                    $(".weekList input[value='" + ary[i] + "']").attr("checked", "checked");
                                }
                            }
                        }
    
                        function initYear(strVal) {
                            var ary = null;
                            var objRadio = $("input[name='year']");
                            if (strVal == "*") {
                                objRadio.eq(1).attr("checked", "checked");
                            } else if (strVal.split('-').length > 1) {
                                ary = strVal.split('-');
                                objRadio.eq(2).attr("checked", "checked");
                                $("#yearStart_0").numberspinner('setValue', ary[0]);
                                $("#yearEnd_0").numberspinner('setValue', ary[1]);
                            }
                        }
    
                    </script>
                    <div>
                    </div>
                </div>
            </div>
            <div>
            </div>
        </div>
    </center>
    </body>
    <script>
        function submit_crontable() {
            var $cron_express = $('[name="cron"]').val();
            var $cron_task=$('[name="cron_task"]').val();
            if ($cron_express.length == 0 || $cron_task.length ==0 ) {
                alert('请检查cron表达式');
            }
            else {
                var $cron_user = $('[name="cron_user"]').val();
                var $cron_desicrible = $('[name="cron_desicrible"]').val();
    
                var cron_data = {
                    "cron_express": $cron_express,
                    "cron_user": $cron_user,
                    "cron_desicrible": $cron_desicrible,
                    'cron_task': $cron_task,
                    'csrfmiddlewaretoken': "{{ csrf_token }}"
    
    
                };
                $.ajax({
                    type: 'post',
                    data: cron_data,
                    success: function (data) {
                        if (data=='ok'){
                            window.location.href='/audit/crontab/{{ host_user_bind.pk }}/'
                        }
                    }
                })
    
            }
        }
    
    </script>
    </html>
    add_crontable.html
    /**
     * 每周期
     */
    function everyTime(dom) {
        var item = $("input[name=v_" + dom.name + "]");
        item.val("*");
        item.change();
    }
    
    /**
     * 不指定
     */
    function unAppoint(dom) {
        var name = dom.name;
        var val = "?";
        if (name == "year")
            val = "";
        var item = $("input[name=v_" + name + "]");
        item.val(val);
        item.change();
    }
    
    function appoint(dom) {
    
    }
    
    /**
     * 周期
     */
    function cycle(dom) {
        var name = dom.name;
        var ns = $(dom).parent().find(".numberspinner");
        var start = ns.eq(0).numberspinner("getValue");
        var end = ns.eq(1).numberspinner("getValue");
        var item = $("input[name=v_" + name + "]");
        item.val(start + "-" + end);
        item.change();
    }
    
    /**
     * 从开始
     */
    function startOn(dom) {
        var name = dom.name;
        var ns = $(dom).parent().find(".numberspinner");
        var start = ns.eq(0).numberspinner("getValue");
        var end = ns.eq(1).numberspinner("getValue");
        var item = $("input[name=v_" + name + "]");
        item.val(start + "/" + end);
        item.change();
    }
    
    function lastDay(dom){
        var item = $("input[name=v_" + dom.name + "]");
        item.val("L");
        item.change();
    }
    
    function weekOfDay(dom){
        var name = dom.name;
        var ns = $(dom).parent().find(".numberspinner");
        var start = ns.eq(0).numberspinner("getValue");
        var end = ns.eq(1).numberspinner("getValue");
        var item = $("input[name=v_" + name + "]");
        item.val(start + "#" + end);
        item.change();
    }
    
    function lastWeek(dom){
        var item = $("input[name=v_" + dom.name + "]");
        var ns = $(dom).parent().find(".numberspinner");
        var start = ns.eq(0).numberspinner("getValue");
        item.val(start+"L");
        item.change();
    }
    
    function workDay(dom) {
        var name = dom.name;
        var ns = $(dom).parent().find(".numberspinner");
        var start = ns.eq(0).numberspinner("getValue");
        var item = $("input[name=v_" + name + "]");
        item.val(start + "W");
        item.change();
    }
    
    $(function() {
        $(".numberspinner").numberspinner({
            onChange:function(){
                $(this).closest("div.line").children().eq(0).click();
            }
        });
    
        var vals = $("input[name^='v_']");
        var cron = $("#cron");
        vals.change(function() {
            var item = [];
            vals.each(function() {
                item.push(this.value);
            });
            //修复表达式错误BUG,如果后一项不为* 那么前一项肯定不为为*,要不然就成了每秒执行了
            //获取当前选中tab
            var currentIndex = 0;
            $(".tabs>li").each(function (i, item) {
                if($(item).hasClass("tabs-selected")){
                    currentIndex =i;
                    return false;
                }
    
            });
            //当前选中项之前的如果为*,则都设置成0
            for (var i = currentIndex; i >= 1; i--) {
                if (item[i] != "*" && item[i - 1] == "*") {
                    item[i - 1] = "0";
                }
            }
            //当前选中项之后的如果不为*则都设置成*
            if (item[currentIndex] == "*") {
                for (var i = currentIndex + 1; i < item.length; i++) {
                    if (i == 5) {
                        item[i] = "?";
                    } else {
                        item[i] = "*";
                    }
                }
            }
            cron.val(item.join(" ")).change();
        });
    
        cron.change(function () {
            btnFan();
            //设置最近五次运行时间
            $.ajax({
                type: 'get',
                url: "CalcRunTime.ashx",
                dataType: "json",
                data: { "CronExpression": $("#cron").val() },
                success: function (data) {
                    if (data && data.length == 5) {
                        var strHTML = "<ul>";
                        for (var i = 0; i < data.length; i++) {
                            strHTML += "<li>" + data[i] + "</li>";
                        }
                        strHTML +="</ul>"
                        $("#runTime").html(strHTML);
                    } else {
                        $("#runTime").html("");
                    }
                }
            });
        });
        
        var secondList = $(".secondList").children();
        $("#sencond_appoint").click(function(){
            if (this.checked) {
                if ($(secondList).filter(":checked").length == 0) {
                    $(secondList.eq(0)).attr("checked", true);
                }
                secondList.eq(0).change();
            }
        });
    
        secondList.change(function() {
            var sencond_appoint = $("#sencond_appoint").prop("checked");
            if (sencond_appoint) {
                var vals = [];
                secondList.each(function() {
                    if (this.checked) {
                        vals.push(this.value);
                    }
                });
                var val = "?";
                if (vals.length > 0 && vals.length < 59) {
                    val = vals.join(",");
                }else if(vals.length == 59){
                    val = "*";
                }
                var item = $("input[name=v_second]");
                item.val(val);
                item.change();
            }
        });
    
        var minList = $(".minList").children();
        $("#min_appoint").click(function(){
            if (this.checked) {
                if ($(minList).filter(":checked").length == 0) {
                    $(minList.eq(0)).attr("checked", true);
                }
                minList.eq(0).change();
            }
        });
        
        minList.change(function() {
            var min_appoint = $("#min_appoint").prop("checked");
            if (min_appoint) {
                var vals = [];
                minList.each(function() {
                    if (this.checked) {
                        vals.push(this.value);
                    }
                });
                var val = "?";
                if (vals.length > 0 && vals.length < 59) {
                    val = vals.join(",");
                }else if(vals.length == 59){
                    val = "*";
                }
                var item = $("input[name=v_min]");
                item.val(val);
                item.change();
            }
        });
        
        var hourList = $(".hourList").children();
        $("#hour_appoint").click(function(){
            if (this.checked) {
                if ($(hourList).filter(":checked").length == 0) {
                    $(hourList.eq(0)).attr("checked", true);
                }
                hourList.eq(0).change();
            }
        });
        
        hourList.change(function() {
            var hour_appoint = $("#hour_appoint").prop("checked");
            if (hour_appoint) {
                var vals = [];
                hourList.each(function() {
                    if (this.checked) {
                        vals.push(this.value);
                    }
                });
                var val = "?";
                if (vals.length > 0 && vals.length < 24) {
                    val = vals.join(",");
                }else if(vals.length == 24){
                    val = "*";
                }
                var item = $("input[name=v_hour]");
                item.val(val);
                item.change();
            }
        });
        
        var dayList = $(".dayList").children();
        $("#day_appoint").click(function(){
            if (this.checked) {
                if ($(dayList).filter(":checked").length == 0) {
                    $(dayList.eq(0)).attr("checked", true);
                }
                dayList.eq(0).change();
            }
        });
        
        dayList.change(function() {
            var day_appoint = $("#day_appoint").prop("checked");
            if (day_appoint) {
                var vals = [];
                dayList.each(function() {
                    if (this.checked) {
                        vals.push(this.value);
                    }
                });
                var val = "?";
                if (vals.length > 0 && vals.length < 31) {
                    val = vals.join(",");
                }else if(vals.length == 31){
                    val = "*";
                }
                var item = $("input[name=v_day]");
                item.val(val);
                item.change();
            }
        });
        
        var mouthList = $(".mouthList").children();
        $("#mouth_appoint").click(function(){
            if (this.checked) {
                if ($(mouthList).filter(":checked").length == 0) {
                    $(mouthList.eq(0)).attr("checked", true);
                }
                mouthList.eq(0).change();
            }
        });
        
        mouthList.change(function() {
            var mouth_appoint = $("#mouth_appoint").prop("checked");
            if (mouth_appoint) {
                var vals = [];
                mouthList.each(function() {
                    if (this.checked) {
                        vals.push(this.value);
                    }
                });
                var val = "?";
                if (vals.length > 0 && vals.length < 12) {
                    val = vals.join(",");
                }else if(vals.length == 12){
                    val = "*";
                }
                var item = $("input[name=v_mouth]");
                item.val(val);
                item.change();
            }
        });
        
        var weekList = $(".weekList").children();
        $("#week_appoint").click(function(){
            if (this.checked) {
                if ($(weekList).filter(":checked").length == 0) {
                    $(weekList.eq(0)).attr("checked", true);
                }
                weekList.eq(0).change();
            }
        });
        
        weekList.change(function() {
            var week_appoint = $("#week_appoint").prop("checked");
            if (week_appoint) {
                var vals = [];
                weekList.each(function() {
                    if (this.checked) {
                        vals.push(this.value);
                    }
                });
                var val = "?";
                if (vals.length > 0 && vals.length < 7) {
                    val = vals.join(",");
                }else if(vals.length == 7){
                    val = "*";
                }
                var item = $("input[name=v_week]");
                item.val(val);
                item.change();
            }
        });
    });
    cron.js
    .icon-blank{
        background:url('icons/blank.gif') no-repeat center center;
    }
    .icon-add{
        background:url('icons/edit_add.png') no-repeat center center;
    }
    .icon-edit{
        background:url('icons/pencil.png') no-repeat center center;
    }
    .icon-remove{
        background:url('icons/edit_remove.png') no-repeat center center;
    }
    .icon-save{
        background:url('icons/filesave.png') no-repeat center center;
    }
    .icon-cut{
        background:url('icons/cut.png') no-repeat center center;
    }
    .icon-ok{
        background:url('icons/ok.png') no-repeat center center;
    }
    .icon-no{
        background:url('icons/no.png') no-repeat center center;
    }
    .icon-cancel{
        background:url('icons/cancel.png') no-repeat center center;
    }
    .icon-reload{
        background:url('icons/reload.png') no-repeat center center;
    }
    .icon-search{
        background:url('icons/search.png') no-repeat center center;
    }
    .icon-print{
        background:url('icons/print.png') no-repeat center center;
    }
    .icon-help{
        background:url('icons/help.png') no-repeat center center;
    }
    .icon-undo{
        background:url('icons/undo.png') no-repeat center center;
    }
    .icon-redo{
        background:url('icons/redo.png') no-repeat center center;
    }
    .icon-back{
        background:url('icons/back.png') no-repeat center center;
    }
    .icon-sum{
        background:url('icons/sum.png') no-repeat center center;
    }
    .icon-tip{
        background:url('icons/tip.png') no-repeat center center;
    }
    
    .icon-mini-add{
        background:url('icons/mini_add.png') no-repeat center center;
    }
    .icon-mini-edit{
        background:url('icons/mini_edit.png') no-repeat center center;
    }
    .icon-mini-refresh{
        background:url('icons/mini_refresh.png') no-repeat center center;
    }
    /static/audit_app/Cron/themes/icon.css
    .icon-blank{
        background:url('icons/blank.gif') no-repeat center center;
    }
    .icon-add{
        background:url('icons/edit_add.png') no-repeat center center;
    }
    .icon-edit{
        background:url('icons/pencil.png') no-repeat center center;
    }
    .icon-remove{
        background:url('icons/edit_remove.png') no-repeat center center;
    }
    .icon-save{
        background:url('icons/filesave.png') no-repeat center center;
    }
    .icon-cut{
        background:url('icons/cut.png') no-repeat center center;
    }
    .icon-ok{
        background:url('icons/ok.png') no-repeat center center;
    }
    .icon-no{
        background:url('icons/no.png') no-repeat center center;
    }
    .icon-cancel{
        background:url('icons/cancel.png') no-repeat center center;
    }
    .icon-reload{
        background:url('icons/reload.png') no-repeat center center;
    }
    .icon-search{
        background:url('icons/search.png') no-repeat center center;
    }
    .icon-print{
        background:url('icons/print.png') no-repeat center center;
    }
    .icon-help{
        background:url('icons/help.png') no-repeat center center;
    }
    .icon-undo{
        background:url('icons/undo.png') no-repeat center center;
    }
    .icon-redo{
        background:url('icons/redo.png') no-repeat center center;
    }
    .icon-back{
        background:url('icons/back.png') no-repeat center center;
    }
    .icon-sum{
        background:url('icons/sum.png') no-repeat center center;
    }
    .icon-tip{
        background:url('icons/tip.png') no-repeat center center;
    }
    
    .icon-mini-add{
        background:url('icons/mini_add.png') no-repeat center center;
    }
    .icon-mini-edit{
        background:url('icons/mini_edit.png') no-repeat center center;
    }
    .icon-mini-refresh{
        background:url('icons/mini_refresh.png') no-repeat center center;
    }
    /static/audit_app/Cron/icon.css
    def add_crontab(request,user_bind_host_id):
        host_user_bind = models.HostUserBind.objects.get(pk=user_bind_host_id)
        if request.method=='POST':
            cron_user=request.POST.get('cron_user')
            cron_desicrible=request.POST.get('cron_desicrible')
            cron_express=request.POST.get('cron_express').strip('')
            linux_cron_express=' '.join(cron_express.split(' ')[1:6])#只取5位数
            print(linux_cron_express)
            cron_task=request.POST.get('cron_task')
            cmd= "echo '%s %s #%s|%s'>> /var/spool/cron/root" %(linux_cron_express,cron_task,cron_user,cron_desicrible)
            current_host_corntable_list = crontab_handler.Crontab_API(host_user_bind).add_crontab(cmd)
            return HttpResponse('ok')
    
        return render(request,'crontab/add_crontable.html',locals())
    views.py

    13.selectize 输入--->搜素--->提示插件

     

    [{'account_no': 717, 'account_level': '3', 'name': '保定长城汽车销售有限公司', 'owner_department': '电销', 'product_name': '长城汽车', 'salesman': 'suyue', 'customer_success': None, 'deal_status': '1', 'lifecycle_stage': '其他'}, {'account_no': 2915, 'account_level': '', 'name': '保定市一划网络科技有限公司', 'owner_department': None, 'product_name': '一划赚', 'salesman': None, 'customer_success': None, 'deal_status': '1', 'lifecycle_stage': '其他'}, {'account_no': 4283, 'account_level': '', 'name': '保定华中技工学校', 'owner_department': '互联网销售-北京', 'product_name': '华中技工', 'salesman': None, 'customer_success': None, 'deal_status': '1', 'lifecycle_stage': '其他'}, {'account_no': 9825, 'account_level': '1', 'name': '保定银行', 'owner_department': '北京KA销售', 'product_name': '', 'salesman': None, 'customer_success': None, 'deal_status': '1', 'lifecycle_stage': '其他'}, {'account_no': 12571, 'account_level': '2', 'name': '保定和社区外包服务有限公司', 'owner_department': '互联网销售-北京', 'product_name': '和社区', 'salesman': None, 'customer_success': None, 'deal_status': '1', 'lifecycle_stage': '其他'}]
    后端返回的json数据[{},{}]
    {% extends "base.html" %}
    {% block title %}测试页面{% end %}
    
    {% block other_js_css %}
    <script src="{{ static_url("js/typeahead.bundle.min.js") }}" type="text/javascript"></script>
    <link rel="stylesheet" type="text/css" href="{{ static_url("css/typeahead.css") }}">
    <script src="{{ static_url("js/selectize.min.js") }}" type="text/javascript"></script>
    <link rel="stylesheet" type="text/css" href="{{ static_url("css/selectize.bootstrap3.min.css") }}">
    <link rel="stylesheet" type="text/css" href="{{ static_url("css/selectize.bootstrap3.min.css.map") }}">
    {% end %}
    {% block content %}
    <div class="container">
        <form action="" method="post">
            <select name="user_list" id="input_account_no">
    
            </select>
               <button type="submit">提交</button>
        </form>
    
    </div>
    {% end %}
    
    {% block more_js %}
    <script>
      $("#input_account_no").selectize(
            {
                valueField: 'account_no',
                labelField: 'name', //返回字典的键一点要根据自己返回的数据来
                searchField: 'name',
                create: false,
                render: {
                    option: function (item, escape) {
                        return '<div>' +
                            '<span class="title">' + escape(item.name) + '</span><br/>' +
                            '<span class="description">客户成功:' + escape(item.customer_success) + '; 销售: ' + escape(item.salesman) + '</span>' +
                            '</div>';
                    }
                },
                load: function (query, callback) {
                    if (!query.length) return callback();
    
                    $.ajax({
                        'type': 'GET',
                        'dataType': 'JSON',
                        'url': '/api/company/search/' + encodeURIComponent(query),
                        'success': function (data) {
                            callback(data);
                        },
                        'error': function (request, status, error) {
                            callback();
                        }
                    });
                }
            });
    
    </script>
    {% end %}
    test.html

    不进行后台搜素模式(多选下拉框)

    {% extends "base.html" %}
    {% block title %}测试页面{% end %}
    
    {% block other_js_css %}
    <script src="{{ static_url("js/typeahead.bundle.min.js") }}" type="text/javascript"></script>
    <link rel="stylesheet" type="text/css" href="{{ static_url("css/typeahead.css") }}">
    <script src="{{ static_url("js/selectize.min.js") }}" type="text/javascript"></script>
    <link rel="stylesheet" type="text/css" href="{{ static_url("css/selectize.bootstrap3.min.css") }}">
    <link rel="stylesheet" type="text/css" href="{{ static_url("css/selectize.bootstrap3.min.css.map") }}">
    {% end %}
    {% block content %}
    <div class="container">
        <form action="" method="post">
            <select name="user_list" id="input_account_no" multiple="multiple">
                <option value="1">唐县</option>
                <option value="1">定州</option>
                <option value="3">高碑店</option>
                <option value="4">保定市</option>
                <option value="5">涞水县</option>
                <option value="6">满城县</option>
            </select>
               <button type="submit">提交</button>
        </form>
    
    </div>
    {% end %}
    
    {% block more_js %}
    <script>
     $('#input_account_no').selectize({plugins: ['remove_button'], delimiter: ',', persist: false});
    </script>
    {% end %}
    多选下拉框

    14.bootstrap3的type ahead 预先输入(模糊搜素功能)

     var hint = hint_dict[column];是arry

    var substringMatcher = function (strs) {
            return function findMatches(q, cb) {
                var matches, substringRegex;
    
                // an array that will be populated with substring matches
                matches = [];
    
                // regex used to determine if a string contains the substring `q`
                substrRegex = new RegExp(q, 'i');
    
                // iterate through the pool of strings and for any string that
                // contains the substring `q`, add it to the `matches` array
                $.each(strs, function (i, str) {
                    if (substrRegex.test(str)) {
                        matches.push(str);
                    }
                });
    
                cb(matches);
            };
        };   
    
    
     function filter_column_onchange() {
            var column = $('#filter_column_name').val();
            console.log(hint_dict)
            var hint = hint_dict[column];
            $('#filter_column_value').typeahead('destroy');
            $('#filter_column_value').typeahead(
                {hint: true, highlight: true, minLength: 1},
                {name: column, source: substringMatcher(hint)}
            );
        }
    js代码

    15.检查用户输入的用户名是否存在?

        function check_customer_id_exist(self) {
            var current_input = self;
            var current_customer_id = $(self).val();
    
            $.ajax({
                'type': 'GET',
                'dataType': 'JSON',
                'url': '/api/customer/exist?customer_id=' + current_customer_id,
                'success': function (data) {
                    if (data['status']) {
                        var $tip_ele = '<p id="customer_id_tip" style="color: red">用户已经存在,请重新输入。</p>';
                        $('#new_form_customer_id')[0].focus();
                        $(current_input).after($tip_ele);
                        setTimeout("$('#customer_id_tip').after().remove();$('#new_form_customer_id').val('')",3000);
                    }
    
                }
            });
    
        }
    检查用户输入的用户名是否存在

    参考

  • 相关阅读:
    120-136. 只出现一次的数字
    119-217. 存在重复元素
    118-103. 二叉树的锯齿形层序遍历
    117.力扣-两数相加问题
    116.python处理xmind文件
    115.python获取服务器信息
    日期转换类 DateConverter.java
    数据库连接工具类——包含取得连接和关闭资源 ConnUtil.java
    数据库连接工具类 数据库连接工具类——仅仅获得连接对象 ConnDB.java
    APP手机端加载不到资源服务器后台解决参考
  • 原文地址:https://www.cnblogs.com/sss4/p/6925370.html
Copyright © 2011-2022 走看看