python 学习笔记十四 jQuery案例详解(进阶篇)

1.选择器和筛选器

案例1

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .hide{
            display: none;
        }
        .coating{
            z-index: 1;
            opacity: 0.5;
            position: fixed;
            background-color: black;
            top: 0;
            right: 0;
            bottom: 0;
            left: 0;
        }
        .modal{
            z-index: 2;
            position: fixed;
            left: 50%;
            top: 50%;
            background-color: #999999;
            width: 400px;
            height: 300px;
            margin-left: -200px;
            margin-top: -150px;
        }
        .filed{
            height: 30px;
            line-height: 30px;
            font-size: 14px;
            display: block;
            margin: 20px 80px;
            overflow: hidden;
        }
        .filed .lb{
            color: #333;
            height: 30px;
            width: 50px;
            float: left;
            margin: 0;
            padding: 0;
            line-height: 30px;
            text-align: left;
        }
        .filed .inp_text{
            height: 30px;
            width: 180px;
            font-size: 14px;
            float: right;
            border: 1px solid #bfbfbf;
            line-height: 30px;
        }
        .filed .buttons{
            font-size: 14px;
            height: 30px;
            line-height: 30px;
            margin-left: 30px;
            padding: 0 20px;
        }

    </style>
</head>
<body>
    <div>
        this is my home page
        <table border="1">
            <thead>
                <tr>
                    <td>主机名</td>
                    <td>IP</td>
                    <td>端口</td>
                    <td onclick="get_prev(this);">编辑</td>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>1</td>
                    <td>2</td>
                    <td>3</td>
                    <td onclick="get_prev(this);">编辑</td>
                </tr>
                <tr>
                    <td>11</td>
                    <td>22</td>
                    <td>33</td>
                    <td onclick="get_prev(this);">编辑</td>
                </tr>
                <tr>
                    <td>111</td>
                    <td>222</td>
                    <td>333</td>
                    <td onclick="get_prev(this);">编辑</td>
                </tr>
            </tbody>
        </table>
    </div>
    <div class="coating hide"></div>
    <div class="modal hide">
        <form>
            <div class="filed">
                <label for="hostname" class="lb">主机名:</label>
                <input class="inp_text" id="hostname" name="hostname" type="text" placeholder="请输入用户名" autocomplete="off">
            </div>
            <div class="filed">
                <label for="port" class="lb">端 口:</label>
                <input class="inp_text" id="port" name="port" type="text" placeholder="端口" autocomplete="off">
            </div>
            <div class="filed">
                <label for="username" class="lb">用户名:</label>
                <input class="inp_text" id="username" name="username" type="text" placeholder="请输入用户名" autocomplete="off">
            </div>
            <div class="filed">
                <input class="buttons" type="submit" value="提交"/>
                <input class="buttons" type="button" onclick="Cancel();" value="取消"/>
            </div>
        </form>
    </div>
    <script type="text/javascript" src="jquery-2.2.3.js"></script>
    <script>
            function get_prev(arg){
                //var li = $(arg).siblings().map(function(){
                //    return $(this).text();
                //});
                var li = [];
                $.each($(arg).prevAll(),function(i) {
                    //this
                    var item = $(arg).prevAll()[i];
                    //$(this).text();
                    var text = $(item).text();
                    li.push(text);
                });
            $("[name=hostname]").val(li[0]);
            $("[name=port]").val(li[1]);
            $("[name=username]").val(li[2]);
            $(".coating").removeClass("hide");
            $(".modal").removeClass("hide");
        }

        function Cancel(){
            $(".coating").addClass("hide");
            $(".modal").addClass("hide");
        }
    </script>
</body>
</html>
模态对话框

jQuery代码:

    <script type="text/javascript" src="jquery-2.2.3.js"></script>
    <script>
        //td编辑标签绑定事件执行get_prev函数
        function get_prev(arg){
            /* 实现:当点击编辑后,弹出对话框,对话框中包含各个td中的值,无法选中出对话框外的其他内容*/
            //存放各td的值
            var li = []; 
            //循环$(arg).prevAll() 这里是找到td编辑上面的所有其他td循环,回调函数function(i) 第一个传入的是数组的下标 
            $.each($(arg).prevAll(),function(i) {
            //item = this 每一个循环的元素td 
            var item = $(arg).prevAll()[i];
            //$(this).text(); 获取td的值
            var text = $(item).text();
            li.push(text);
            });      
            // 获取各td的值,首先要获取编辑td的标签,然后获取除他外,同级的标签(sibliings获取除自身外的同辈元素)
            // 取到的是一个数组,遍历数组text取值,将值赋给对话框通过val(val获取或设置匹配元素的当前值。)
            //var li = $(arg).siblings().map(function(){
            //    return $(this).text();
            //});
            var new_li = li.reverse();
            $("[name=hostname]").val(new_li[0]);
            $("[name=port]").val(new_li[1]);
            $("[name=username]").val(new_li[2]);
            //2.移除遮盖层的隐藏class,默认添加hideclass removeClass去掉即可   
            $(".coating").removeClass("hide");
            //3.显示模态对话框
            $(".modal").removeClass("hide");
        }
        //点击取消,将模态对话框和遮盖层隐藏起来
        function Cancel(){
            $(".coating").addClass("hide");
            $(".modal").addClass("hide");
        }
    </script>

效果如下:

案例2.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .hide{
            display: none;
        }
        .coating{
            z-index: 1;
            opacity: 0.5;
            position: fixed;
            background-color: black;
            top: 0;
            right: 0;
            bottom: 0;
            left: 0;
        }
        .load{
            z-index: 2;
            position: fixed;
            left: 50%;
            top: 50%;
            margin-left: -16px;
            margin-top: -16px;
        }
    </style>
</head>
<body>
    <div>
        <input onclick="loading();" type="button" value="加载对话框"/>
    </div>
    <div class="coating hide"></div>
    <div class="load">
         <img src="loading_32.gif"/>
    </div>
    <script type="text/javascript" src="jquery-2.2.3.js"></script>
    <script>
        //加载框同模态对话框相似,input标签加载对话框绑定事件 触发后去掉遮盖层和加载框层即可
        function loading(){
            $(".coating").removeClass("hide"); //removeClass去除匹配标签的class
            $(".load").removeClass("hide"); 
        }
    </script>
</body>
</html>
加载对话框

jQuery代码:

//同上,显示遮盖层和加载框即可
function loading(){ $(".coating").removeClass("hide"); $(".load").removeClass("hide"); }

效果如下:

 案例3.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        body{
            margin: 0 auto;
        }
        .menu{
            float: left;width: 30%;height: 500px;
        }
        .content{
            float: left;width: 70%;height: 500px;
        }
        .title{
            background-color: black;
            color: white;
            height: 40px;
            line-height: 40px;
        }
        .hide{
            display: none;
        }
        .c{
            margin-left: 10px;
        }
    </style>

</head>
<body>
    <div class="menu">
        <div>
            <div class="title" onclick="Func(this);">菜单一</div>
                <div class="c">
                    <div>1.1</div>
                    <div>1.2</div>
                    <div>1.3</div>
                </div>
        </div>
        <div>
            <div class="title" onclick="Func(this);">菜单二</div>
                <div class="c hide">
                    <div>2.1</div>
                    <div>2.2</div>
                    <div>2.3</div>
                </div>
        </div>
        <div>
            <div class="title" onclick="Func(this);">菜单三</div>
                <div class="c hide">
                    <div>3.1</div>
                    <div>3.2</div>
                    <div>3.3</div>
                </div>
        </div>
    </div>
    <div class="content"></div>

    <script type="text/javascript" src="jquery-2.2.3.js"></script>
    <script>
        function Func(ths){
            $(ths).next().removeClass("hide");
            $(ths).parent().siblings().find(".c").addClass("hide");
        }
    </script>
</body>
</html>
左侧菜单

jQuery代码:

/*  需求: 
    通过点击其中一个标签的时候,显示其标签内的内容,并且隐藏其他标签内容。
    默认第一个菜单默认显示;其他两个菜单是隐藏的。
    如何判断我点击的是哪一个菜单呢? 为函数传入参数this $(this)获取当前点击的标签
*/        
function Func(ths){
    //$(ths) 表示当前点击的标签
  //var t = $(ths).text();
  //console.log(t);
   //1.获取点击当前标签
   //2.将它的下一级标签显示
   //3.将它同级标签的下一级标签隐藏
   $(ths).next().removeClass("hide"); 
   //$(ths)获取当前标签,next()查找下一个同辈元素(菜单下的子菜单),removeClass("hide")显示子菜单(移除标签样式) 此时点击标签的子标签将显示,接下来隐藏其他同级的子标签
   $(ths).parent().siblings().find(".c").addClass("hide"); 
   //将当前标签的父级标签取出(即该例的菜单一),siblings查找同级标签(菜单二,菜单三),find(".c")查找同级标签下所有包含c的class(同级菜单下的子菜单),addClass("hide")隐藏子菜单
}

效果图如下:

案例4

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .tab-box .box-menu{
            background-color: #9b9b9b;
            border: 1px solid #9b9b9b;
        }
        .tab-box .box-body{
            border: 1px solid #9b9b9b;
        }
        .hide{
            display: none;
        }
        .current{
            background-color: red;
            color:white;
        }
    </style>
</head>
<body>
    <div class="tab-box">
        <div class="box-menu">
            <!--所有菜单-->
            <a alex="c1" onclick="ChangeTab(this);" class="current">菜单一</a>
            <a alex="c2" onclick="ChangeTab(this);">菜单二</a>
            <a alex="c3" onclick="ChangeTab(this);">菜单三</a>
        </div>
        <div class="box-body">
            <!--所有内容-->
            <div id="c1">内容一</div>
            <div id="c2" class="hide">内容二</div>
            <div id="c3" class="hide">内容三</div>
        </div>
    </div>
    <script src="jquery-2.2.3.js"></script>
    <script>
        function ChangeTab(arg){
            $(arg).addClass("current").siblings().removeClass("current");
            //获取当前点击标签$(arg)
            var contenId = $(arg).attr("alex");
            var temp = "#" + contenId;
            $(temp).removeClass("hide").siblings().addClass("hide");
            //获取当前标签的属性 alex 对应的值
            // 值 $("#值") 显示,其他兄弟隐藏
        }
    </script>
</body>
</html>
tab菜单

jQuery代码:

function ChangeTab(arg){
//点击其中一个菜单时加上样式,另外两个菜单去掉样式
  $(arg).addClass("current").siblings().removeClass("current"); //菜单栏属性同内容栏id的值关联
//获取当前点击标签$(arg)的关联属性本例“alex” var contenId = $(arg).attr("alex"); var temp = "#" + contenId; //字符串拼接 $(temp).removeClass("hide").siblings().addClass("hide"); //获取当前标签的属性 alex 对应的值 // 值 $("#值") 显示,其他兄弟隐藏 }

效果如下:

2.属性和css

案例1.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <style>
        .back{
            position: fixed;
            bottom: 0px;
            right: 0px;
        }
        .hide{
            display: none;
        }
    </style>
</head>
<body>

<div style="height: 2000px;"></div>

<div onclick="GoTop()" class="back hide">返回顶部</div>

<script src="jquery-1.8.2.js"></script>
<script type="text/javascript">

    function GoTop(){
        //返回顶部
        $(window).scrollTop(0);
    }

    $(function(){

        $(window).scroll(function(){
            //当滚动滑轮时,执行函数体

            //获取当前滑轮滚动的高度
            var top = $(window).scrollTop();

            if(top>100){
                //展示“返回顶部”
                $('.back').removeClass('hide');
            }else{
                //隐藏“返回顶部”
                $('.back').addClass('hide');
            }
        });
    });

</script>

</body>
</html>
返回顶部

jQuery代码:

function GoTop(){
    //返回顶部( scrollTop 获取匹配元素(window窗体)相对滚动条顶部的偏移)
    $(window).scrollTop(0);
}
//滚动条事件需在页面加载的时候就执行,定义自执行函数(function(){}()) $(function(){
//当用户滚动指定的元素时,会发生 scroll 事件。 $(window).scroll(function(){ //当滚动滑轮时,执行函数体      //获取当前滑轮滚动的高度 var top = $(window).scrollTop();
//滚动高度超过100时 if(top>100){ //展示"返回顶部" $(".back").removeClass("hide"); }else{ //隐藏"返回顶部" $(".back").addClass("hide"); } }); });
</script>

效果图如下:

案例2

<!DOCTYPE html>
<html>
    <head>
        <meta charset='utf-8' />
        <title></title>
        <script type="text/javascript" src='jquery-1.8.2.js'></script>
        <script type="text/javascript">
            $(function(){
                $('#selectAll').click(function(){
                    $('#checklist :checkbox').prop('checked',true);
                })
                $('#unselectAll').click(function(){
                    $('#checklist :checkbox').prop('checked',false);
                })
                $('#reverseAll').click(function(){
                    $('#checklist :checkbox').each(function(){
                        $(this).prop('checked',!$(this).prop('checked'))
                    })
                })

            })            
        </script>
    </head>
    <body>
        <div id='checklist'>
            <input type='checkbox' value='1'/>篮球
            <input type='checkbox' value='2'/>足球
            <input type='checkbox' value='3'/>羽毛球
        </div>
        <input type='button' value='全选' id='selectAll' />
        <input type='button' value='不选' id='unselectAll' />
        <input type='button' value='反选' id='reverseAll' />
    </body>
</html>
多选,不选,取消

jQuery代码:

    $(function(){
//全选按钮绑定事件 $('#selectAll').click(function(){
//将id=checklist下的checkbox复选框设置checked属性为true $('#checklist :checkbox').prop('checked',true); //prop获取或设置在匹配的元素集中的第一个元素的属性值,专用来处理checkbox和radio. })
//不选按钮绑定事件 $('#unselectAll').click(function(){
//将id=checklist下的checkbox复选框设置checked属性为false $('#checklist :checkbox').prop('checked',false); }) $('#reverseAll').click(function(){
////遍历id=checklist下的checkbox复选框 $('#checklist :checkbox').each(function(){
//将获取到的checked属性设置为相反的值 $(this).prop('checked',!$(this).prop('checked'))
//if($(this).prop("checked")){
        // $(this).prop("checked", false)
          //}else{
       // $(this).prop("checked", true)
//}
}); }); });

案例3

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <style>
        .show{
            position: fixed;
            top:10px;
            right:10px;
        }
    </style>
</head>
<body>
    <div id="cp" class="show">Go</div>
    <div class="c1" style="height: 500px">
        <h1>第一章</h1>
    </div>
    <div class="c1" style="height: 1000px">
        <h1>第二章</h1>
    </div>
    <div class="c1" style="height: 30px">
        <h1>第三章</h1>
    </div>
    <script src="jquery-2.2.3.js" type="text/javascript"></script>
    <script>
        $(function() {
            $(window).scroll(function(){
                //捕获滚动条当前离顶部高度
                var scroll_top = $(window).scrollTop();
                //存放各个章节scroll高度
                var list = [];
                $.each($(".c1"), function(i){
                    //offset 获取当前标签离顶部的top和left
                    var c_top = $($(".c1")[i]).offset().top;
                    list.push(c_top);
                });
                $.each(list, function(i){
                    //滚动条高度+窗体高度 = 整个页面高度
                    if(scroll_top + $(window).height() == $(document).height()){
                        $("#cp").text($(".c1").last().text());
                        return
                    }
                    //滚动条大于标签离顶部的高度
                    if(scroll_top > list[i]){
                        $("#cp").text($($(".c1")[i]).text());
                        return
                    }
                });
            });
        });
    </script>
</body>
</html>
滚动条1

jQuery代码:

$(function() {
    $(window).scroll(function(){
        //捕获滚动条当前离顶部高度
        var scroll_top = $(window).scrollTop();
        //存放各个章节scroll高度
        var list = [];
//遍历所有的c1标签,此例中的每个章节所占高度 $.each($(".c1"), function(i){ //offset 获取当前标签离顶部的top和left var c_top = $($(".c1")[i]).offset().top; //($(".c1")[i]遍历中的每个标签 list.push(c_top); //放入数组 });
//遍历数组同当前滚动条高度作比较 $.each(list, function(i){ //滚动条高度+窗体高度 = 整个页面高度 解析:当窗体没有滚动条的时候,窗体就是整个页面的高度;当出现滚动条的时候,滚动条的高度即窗体剩下的内容(无法在窗体显示完整)+
//窗体的高度(显示的内容) = 整个页面的高度。 if(scroll_top + $(window).height() == $(document).height()){ //当滚动条拉动最底部的时候,显示最后一章
       $("#cp").text($(".c1").last().text());
//显示一次即退出循环 return }; //滚动条大于标签离顶部的高度 if(scroll_top > list[i]){ $("#cp").text($($(".c1")[i]).text()); //将显示章节切换的内容同实际循环到的标签的文本内容进行更换 //显示一次退出循环
       return }; }); }); });
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>

        body{
            margin: 0px;
        }
        img {
            border: 0;
        }
        ul{
            padding: 0;
            margin: 0;
            list-style: none;
        }
        .clearfix:after {
            content: ".";
            display: block;
            height: 0;
            clear: both;
            visibility: hidden;
        }

        .wrap{
            width: 980px;
            margin: 0 auto;
        }

        .pg-header{
            background-color: #303a40;
            -webkit-box-shadow: 0 2px 5px rgba(0,0,0,.2);
            -moz-box-shadow: 0 2px 5px rgba(0,0,0,.2);
            box-shadow: 0 2px 5px rgba(0,0,0,.2);
        }
        .pg-header .logo{
            float: left;
            padding:5px 10px 5px 0px;
        }
        .pg-header .logo img{
            vertical-align: middle;
            width: 110px;
            height: 40px;

        }
        .pg-header .nav{
            line-height: 50px;
        }
        .pg-header .nav ul li{
            float: left;
        }
        .pg-header .nav ul li a{
            display: block;
            color: #ccc;
            padding: 0 20px;
            text-decoration: none;
            font-size: 14px;
        }
        .pg-header .nav ul li a:hover{
            color: #fff;
            background-color: #425a66;
        }
        .pg-body{

        }
        .pg-body .catalog{
            position: absolute;
            top:60px;
            width: 200px;
            background-color: #fafafa;
            bottom: 0px;
        }
        .pg-body .catalog.fixed{
            position: fixed;
            top:10px;
        }

        .pg-body .catalog .catalog-item.active{
            color: #fff;
            background-color: #425a66;
        }

        .pg-body .content{
            position: absolute;
            top:60px;
            width: 700px;
            margin-left: 210px;
            background-color: #fafafa;
            overflow: auto;
        }
        .pg-body .content .section{
            height: 500px;
        }
    </style>
</head>
<body>

    <div class="pg-header">
        <div class="wrap clearfix">
            <div class="logo">
                <a href="#">
                    <img src="http://core.pc.lietou-static.com/revs/images/common/logo_7012c4a4.pn">
                </a>
            </div>
            <div class="nav">
                <ul>
                    <li>
                        <a  href="#">首页</a>
                    </li>
                    <li>
                        <a  href="#">功能一</a>
                    </li>
                    <li>
                        <a  href="#">功能二</a>
                    </li>
                </ul>
            </div>

        </div>
    </div>
    <div class="pg-body">
        <div class="wrap">
            <div class="catalog">
                <div class="catalog-item" auto-to="function1"><a>第1章</a></div>
                <div class="catalog-item" auto-to="function2"><a>第2章</a></div>
                <div class="catalog-item" auto-to="function3"><a>第3章</a></div>
            </div>
            <div class="content">

                <div menu="function1" class="section">
                    <h1>第一章</h1>
                </div>
                <div menu="function2" class="section">
                    <h1>第二章</h1>
                </div>
                <div menu="function3" class="section">
                    <h1>第三章</h1>
                </div>
            </div>
        </div>
    </div>
    <script src="jquery-2.2.3.js"></script>
    <script>
        window.onscroll = function(){
            var ws = $(window).scrollTop();
            if(ws>50){
                $(".catalog").addClass("fixed");
            }else{
                $(".catalog").removeClass("fixed");
            }
            $(".content").children().each(function(){
                var offs = $(this).offset();
                var offTop = offs.top;
                //当前标签离顶部高度 < 滚动条高度
                //当前标签离顶部高度+当前标签的高度 > 滚动条高度
                var total = offTop + $(this).height();
                if($(window).scrollTop()+$(window).height() == $(document).height()){
                    $(".catalog").children(":last").css("fontSize","48px").siblings().css("fontSize","12px");
                }
                if(ws > offTop && total > ws){
                    var t = $(this).attr("menu");
                    var target = 'div[auto-to="'+ t + '"]';
                    $(".catalog").children(target).css("fontSize","48px").siblings().css("fontSize","12px");
                    return;
                };
            });
        };
    </script>
</body>
</html>
滚动条2

html代码:

    <div class="pg-body">
        <div class="wrap">
            <div class="catalog">
                <div class="catalog-item" auto-to="function1"><a>第1章</a></div>
                <div class="catalog-item" auto-to="function2"><a>第2章</a></div>
                <div class="catalog-item" auto-to="function3"><a>第3章</a></div>
            </div>
            <div class="content">
                //思考:如何将左侧标签栏中的章节同内容中的章节关联起来? 利用自定义属性在标签栏利用auto-to属性 同内容中的menu属性关联
                <div menu="function1" class="section">
                    <h1>第一章</h1>
                </div>
                <div menu="function2" class="section">
                    <h1>第二章</h1>
                </div>
                <div menu="function3" class="section">
                    <h1>第三章</h1>
                </div>
            </div>
        </div>
    </div>

jQuery代码:

   window.onscroll = function(){
//获取滚动条scroll的高度
var ws = $(window).scrollTop(); //下拉滚动条大于50像素 将左侧菜单栏跟随滚动条一起动
if(ws>50){ $(".catalog").addClass("fixed"); }else{ $(".catalog").removeClass("fixed"); }
//找到内容框中所有的章节div $(".content").children().each(function(){
//计算当前标签距离窗体的高度 var offs = $(this).offset(); var offTop = offs.top;
var total = offTop + $(this).height(); //当前标签离顶部高度 + 当前标签的高度 = 整个当前标签的范围
//滚动条高度+窗体高度 = 整个页面高度 解析:当窗体没有滚动条的时候,窗体就是整个页面的高度;当出现滚动条的时候,滚动条的高度即窗体剩下的内容(无法在窗体显示完整)+
//窗体的高度(显示的内容) = 整个页面的高度。
if($(window).scrollTop()+$(window).height() == $(document).height()){ $(".catalog").children(":last").css("fontSize","48px").siblings().css("fontSize","12px"); }
//当前标签离顶部高度 < 滚动条高度 表示显示的是下一章节 //当前标签离顶部高度 + 当前标签的高度 > 滚动条高度 表示滚动条还处于当前标签的范围,超出后将显示下一章 if(ws > offTop && total > ws){
//关联内容中章节同标签中的章节 var t = $(this).attr("menu"); //找到内容框中当前章节的menu属性值 var target = 'div[auto-to="'+ t + '"]'; //拼接字符串 $(".catalog").children(target).css("fontSize","48px").siblings().css("fontSize","12px"); //查找标签栏中对应的章节改变css return; //显示一次退出循环,否则循环相同的内容。 }; }); };

3.事件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <input type="button" value="添加" onclick="AddContent();"/>
    <div onclick="func()"></div>
    <div>
        <ul>
            <li>1</li>
            <li>2</li>
            <li>3</li>
            <li>4</li>
            <li>5</li>
            <li>6</li>
            <li>7</li>
        </ul>
    </div>
    <script src="jquery-2.2.3.js"></script>
    <script>
        function AddConten(){
            $("ul").append("<li>8<li>");
        };
        function func(){
        };
        //当前文档准备就绪
        $(document).ready(function(){
        });
        $(function(){
            //最基本的jQuery事件绑定
            //立即绑定事件
//            $("li").click(function(){
//                var temp = $(this).text();
//                alert(temp);
//            });
            //绑定事件 等同于onclick
//            $("li").bind("click",function(){
//                var temp = $(this).text();
//                alert(temp);
//            });
            //事件委托,不立即绑定事件,只会在事件触发的时候临时绑定
            $("ul").delegate("li","click",function(){
                var temp = $(this).text();
                alert(temp);
            })
        });

    </script>
</body>
</html>
事件基本

jQuery代码:

function AddConten(){
  $("ul").append("
<li>8<li>"); };
//window.onscroll = function(){ }; //当前文档准备就绪 $(document).ready(function(){ }); $(function(){ //最基本的jQuery事件绑定 //立即绑定事件 //$("li").click(function(){ //var temp = $(this).text(); //alert(temp); //}); //绑定事件 等同于onclick //$("li").bind("click",function(){ // var temp = $(this).text(); // alert(temp); //}); //事件委托,不立即绑定事件,只会在事件触发的时候临时绑定 $("ul").delegate("li","click",function(){ var temp = $(this).text(); alert(temp); }); });

案例1

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <div style="border: 1px solid #ddd;width: 600px;position: absolute;">
        <div id="title" style="background-color: black;height: 40px;color: white;">
            标题
        </div>
        <div style="height: 300px;">
            内容
        </div>
    </div>
    <script type="text/javascript" src="jquery-2.2.3.js"></script>
    <script>
        $(function(){
            //页面加载完成后自动执行
            //jquery链式编写,即一个selector可以绑定多个事件
            //绑定鼠标覆盖事件,当鼠标移动到移动面板时,改变鼠标指针
            $("#title").mouseover(function(){
                $(this).css("cursor","move");
            }).mousedown(function(e){ //在#title选择器绑定鼠标点击事件
                //e特殊返回值包含鼠标的x,y坐标
                //console.log($(this).offset());
                //有些浏览器不支持event需要手动指定
                var _event = e || window.event;
                //原始鼠标横纵坐标位置
                var old_x = _event.clientX;
                var old_y = _event.clientY;
                //移动窗体的位置
                var parent_left = $(this).parent().offset().left;
                var parent_top = $(this).parent().offset().top;
                //绑定鼠标移动事件
                $(this).bind("mousemove",function(e){
                    //有些浏览器不支持event需要手动指定
                    var _new_event = e || window.event;
                    //新的鼠标横纵坐标位置
                    var new_x = _new_event.clientX;
                    var new_y = _new_event.clientY;
                    //移动窗体的位置
                    var x = parent_left + (new_x - old_x);
                    var y = parent_top + (new_y - old_y);
                    //$(this)等于title标签层,找到它的上一层 移动面板 更改位置 postion:absolute;left:x px;top: y px;
                    $(this).parent().css("left",x+"px");
                    $(this).parent().css("top",y+"px");
                })
            }).mouseup(function(){//绑定鼠标松开事件
                $(this).unbind("mousemove");//解除鼠标移动绑定事件
            });
        });
    </script>
</body>
</html>
移动面板

jQuery代码:

$(function(){
    //页面加载完成后自动执行
    //jquery链式编写,即一个selector可以绑定多个事件
    //绑定鼠标覆盖事件,当鼠标移动到移动面板时,改变鼠标指针
    $("#title").mouseover(function(){
        $(this).css("cursor","move");
        }).mousedown(function(e){ //在#title选择器绑定鼠标点击事件
        //e特殊返回值包含鼠标的x,y坐标
        //console.log($(this).offset());
        //有些浏览器不支持event需要手动指定
        var _event = e || window.event;
        //原始鼠标横纵坐标位置
        var old_x = _event.clientX;
        var old_y = _event.clientY;
        //移动窗体的位置
        var parent_left = $(this).parent().offset().left;
        var parent_top = $(this).parent().offset().top;
        //绑定鼠标移动事件
        $(this).bind("mousemove",function(e){
        //有些浏览器不支持event需要手动指定
        var _new_event = e || window.event;
        //新的鼠标横纵坐标位置
        var new_x = _new_event.clientX;
        var new_y = _new_event.clientY;
        //移动窗体的位置
        var x = parent_left + (new_x - old_x);
        var y = parent_top + (new_y - old_y);
        //$(this)等于title标签层,找到它的上一层 移动面板 更改位置 postion:absolute;left:x px;top: y px;
        $(this).parent().css("left",x+"px");
        $(this).parent().css("top",y+"px");
        })
    }).mouseup(function(){//绑定鼠标松开事件
        $(this).unbind("mousemove");//解除鼠标移动绑定事件
        });
});

效果图如下:

4.ajax

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
// ajax提交数据
<input id="n1" name="pp" /> <input type="button" value="提交" onclick="SubmitData();"/> //form提交数据 <form action="" method="post"> <p><input type="text" name="user"/></p> <p><input type="password" name="pwd" /></p> <input type="submit" /> </form> <script src="jquery-2.2.3.js"></script> <script> function SubmitData(){ // 获取值 var inpVal = $('#n1').val(); var inpName = $('#n1').attr('name'); $.ajax({
//等同于form中action url url:
"http://127.0.0.1:8000/index/",
//提交的数据:
data
//发送到服务器的数据。将自动转换为请求字符串格式。GET 请求中将附加在 URL 后。查看 processData 选项说明以禁止此自动转换。
//必须为 Key/Value 格式。如果为数组,jQuery 将自动为不同值对应同一个名称。如 {foo:["bar1", "bar2"]} 转换为 "&foo=bar1&foo=bar2"。 data: {'kk': 123, inpName: inpVal}, type: 'POST', //form中的method success: function(arg){ // 当请求执行完成之后,自动调用 // arg,服务器返回的数据 console.log(arg); }, error: function(){ // 当请求错误之后,自动调用 } }) } </script> </body> </html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>

    <input type="button" value="获取节目" onclick="SubmitData();"/>

    <div id="container">

    </div>

    <script src="jquery-2.2.3.js"></script>
    <script>
        function SubmitData(){
            // 获取值
            $.ajax({
                url: "http://www.jxntv.cn/data/jmd-jxtv2.html",
                data: {},
                type: 'GET',
                dataType: 'jsonp',
                jsonp: 'callback',
                jsonpCallback: 'list',
                success: function(arg){
                    console.log(arg);
                    // arg = {data: xxx}
                    // 当请求执行完成之后,自动调用
                    // arg,服务器返回的数据
                    var jsonpArray = arg.data;
                    $.each(jsonpArray, function(k,v){
                        // k,下标
                        // v,数组值
                        var week = v.week;
                        var temp = "<h1>" + week + "</h1>";
                        $('#container').append(temp);
                        var listArray = v.list;
                        $.each(listArray, function(kk, vv){
                            var link = vv.link;
                            var name = vv.name;
                            var tempNew = "<a href='" + link + "'>" + name + "</a><br/>";
                            $('#container').append(tempNew);
                        })
                    })

                },
                error: function(){
                    // 当请求错误之后,自动调用
                }
            })
        }
    </script>
</body>
</html>
ajax jsonp

jQuery代码:

function SubmitData(){
    // 获取值
    $.ajax({
        url: "http://www.jxntv.cn/data/jmd-jxtv2.html", //数据查询API
        data: {}, 
        type: 'GET',
        dataType: 'jsonp', //预期服务器返回的数据类型.
//"jsonp": JSONP 格式。使用 JSONP 形式调用函数时,如 "myurl?callback=?" jQuery 将自动替换 ? 为正确的函数名,以执行回调函数。 jsonp: 'callback',
//在一个jsonp请求中重写回调函数的名字。这个值用来替代在"callback=?"这种GET或POST请求中URL参数里的"callback"部分,
//比如{jsonp:'onJsonPLoad'}会导致将"onJsonPLoad=?"传给服务器。 jsonpCallback: 'list',
//
为jsonp请求指定一个回调函数名。这个值将用来取代jQuery自动生成的随机函数名。这主要用来让jQuery生成度独特的函数名,
//这样管理请求更容易,也能方便地提供回调函数和错误处理。你也可以在想让浏览器缓存GET请求的时候,指定这个回调函数名。 success: function(arg){ console.log(arg);
// Object {data: Array[7]} // arg = {data: xxx} // 当请求执行完成之后,自动调用 // arg,服务器返回的数据 var jsonpArray = arg.data; //获取返回数据(数组) $.each(jsonpArray, function(k,v){ // k,下标 // v,数组值 var week = v.week; var temp = "
<h1>" + week + "</h1>"; $('#container').append(temp);
//Object list:Array[19] week:"周日" var listArray = v.list; //获取每日数据(数组) $.each(listArray, function(kk, vv){ var link = vv.link; //节目link var name = vv.name; //节目name var tempNew = "
<a href='" + link + "'>" + name + "</a><br/>"; //为节目添加a标签 $('#container').append(tempNew); //添加在每天下面 }) }) }, error: function(){ // 当请求错误之后,自动调用 } }) }

效果如下:

 

Form表单案例

比较常用的form表单编辑,包含全选,反选,取消,编辑模式几个操作,

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        .edit-mode{
            background-color: #b3b3b3;
            padding: 8px;
            text-decoration: none;
            color: white;
        }
        .editing{
            background-color: #f0ad4e;
        }
    </style>
</head>
<body>

    <div style="padding: 20px">
        <input type="button" onclick="CheckAll('#edit_mode', '#tb1');" value="全选" />
        <input type="button" onclick="CheckReverse('#edit_mode', '#tb1');" value="反选" />
        <input type="button" onclick="CheckCancel('#edit_mode', '#tb1');" value="取消" />

        <a id="edit_mode" class="edit-mode" href="javascript:void(0);" onclick="EditMode(this, '#tb1');" >进入编辑模式</a>

    </div>
    <table border="1">
        <thead>
        <tr>
            <th>选择</th>
            <th>主机名</th>
            <th>端口</th>
            <th>业务</th>
            <th>状态</th>
        </tr>
        </thead>
        <tbody id="tb1">
            <tr>
                <td><input type="checkbox" /></td>
                <td edit="true">v1</td>
                <td>v11</td>
                <td edit="true" edit-type="select" select-val="1" global-key="BUSINESS">车上会</td>
                <td edit="true" edit-type="select" select-val="1" global-key="STATUS">在线</td>
            </tr>
            <tr>
                <td><input type="checkbox" /></td>
                <td edit="true">v11</td>
                <td>v11</td>
                <td edit="true" edit-type="select" select-val="2" global-key="BUSINESS">二手车</td>
                <td edit="true" edit-type="select" select-val="2" global-key="STATUS">下线</td>
            </tr>
            <tr>
                <td><input type="checkbox" /></td>
                <td edit="true">v111</td>
                <td>v11</td>
                <td edit="true" edit-type="select" select-val="3" global-key="BUSINESS">大保健</td>
                <td edit="true" edit-type="select" select-val="2" global-key="STATUS">下线</td>
            </tr>
        </tbody>
    </table>
    <script type="text/javascript" src="jquery-2.2.3.js"></script>
    <script>

        STATUS = [
            {'id': 1, 'text': "在线"},
            {'id': 2, 'text': "下线"}
        ];
        BUSINESS = [
            {'id': 1, 'text': "车上会"},
            {'id': 2, 'text': "二手车"},
            {'id': 3, 'text': "大保健"}
        ];
        //console.log(STATUS);
        //console.log(window["STATUS"]);

        $(function(){
            $("#tb1").find(":checkbox").click(function(){
                var tr = $(this).parent().parent();
                var isEditing = $("#edit_mode").hasClass("editing");
                //进入编辑
                if(isEditing){
                    //判断是否已经选中
                    //先执行默认的事件
                    if($(this).prop("checked")){
                        //当前行进入编辑状态
                        RowIntoEditMode(tr);
                    }else{
                        //当前行退出编辑状态
                        RowOutEditMode(tr);
                    }
                }
            });
        });

        globalCtrlKeyPress = false;

        window.onkeydown = function(event){
            console.log(event.keyCode);
            if(event && event.keyCode==17){
                window.globalCtrlKeyPress = true;
            }else{
                window.globalCtrlKeyPress = false;
            }
        };

        function MultiChange(ths){
            //检测是否按下ctrl键
            if(window.globalCtrlKeyPress == true){
                //td所在的tr中的索引位置目的是修改该列为统一的值
                var index = $(ths).parent().index();
                var value = $(ths).val();
                $(ths).parent().parent().nextAll().find("td input[type='checkbox']:checked").each(function(){
                    $(this).parent().parent().children().eq(index).children().val(value);
                })
            }
        }

        function CheckAll(mode,tb){
            //选中checkbox
            //如果已经进入编辑模式,让选中行进入编辑模式
            //tb = #tb1
            $(tb).children().each(function(){
                //$(this)循环每一个tr
                //查找tr下面的checkbox是否被选中
                var tr = $(this);
                var isChecked = $(this).find(":checkbox").prop("checked");
                if(isChecked == true){
                }else{
                    //复选框未选中,选中
                    $(this).find(":checkbox").prop("checked",true);
                    //查看是否进入编辑状态
                    var isEditing = $(mode).hasClass("editing");
                    //进入编辑
                    if(isEditing){
                        //进入编辑状态,循环每一个可以编辑的td
                        RowIntoEditMode(tr);
//                        tr.children().each(function(){
//                            var td = $(this);
//                            if(td.attr("edit") == "true"){
//                                var text = td.text();
//                                var temp = "<input type='text' value='" + text + "'/>";
//                                td.html(temp);
//                            }
//                        })
                    }
                }
            })
        }

        function CheckCancel(mode,tb){
            // 取消选中checkebox
            //如果已经进入编辑模式,行退出编辑状态
            $(tb).children().each(function(){
                var tr = $(this);
                if(tr.find(":checkbox").prop("checked")){
                    //移除选中
                    tr.find(":checkbox").prop("checked",false);
                    var isEditing = $(mode).hasClass("editing");
                    if(isEditing == true){
                        //当前行,退出编辑状态
                        RowOutEditMode(tr);
//                        tr.children().each(function(){
//                            var td = $(this);
//                            if(td.attr("edit") == "true"){
//                                var inp = td.children(":first");
//                                var inp_value = inp.val();
//                                $(this).text(inp_value);
//                            }
//                        })
                    }
                }
            })
        }

        function CheckReverse(mode,tb){
            //是否进入编辑模式
            if($(mode).hasClass("editing")){
                $(tb).children().each(function(){
                    //遍历所有tr
                    var tr = $(this);
                    //找到tr的第一个td 复选框,判断是否被选中
                    var check_box = tr.children().first().find(":checkbox");
                    if(check_box.prop("checked")){
                        check_box.prop("checked", false); //选中,设置为未选中
                        //当前行,退出编辑状态
                        RowOutEditMode(tr);
//                        tr.children().each(function(){
//                            var td = $(this);
//                            if(td.attr("edit") == "true"){
//                                var inp = td.children(":first");
//                                var inp_value = inp.val();
//                                $(this).text(inp_value);
//                            }
//                        })
                    }
                    else{
                        check_box.prop("checked",true);
                        //当前行,进入编辑状态
                        RowIntoEditMode(tr);
//                        tr.children().each(function(){
//                            var td = $(this);
//                            if (td.attr("edit") == "true") {
//                                var text = td.text();
//                                var temp = "<input type='text' value='" + text + "'/>";
//                                td.html(temp);
//                            }
//                        })
                    }
                });
            }else{
                //未进入编辑状态,只需要修改复选框的状态即可
                $(tb).children().each(function(){
                    var tr=$(this);
                    var check_box = tr.children().first().find(":checkbox");
                    if(check_box.prop('checked')){
                        check_box.prop("checked",false);
                    }else{
                        check_box.prop("checked",true);
                    }
                });
            }
        }

        function EditMode(ths,tb){
            var isediting = $(ths).hasClass("editing");
            if(isediting){
                $(ths).text("进入编辑模式");
                $(ths).removeClass("editing");
                $(tb).children().each(function() {
                    //$(this)循环每一个tr
                    //查找tr下面的checkbox是否被选中
                    var tr = $(this);
                    if (tr.find(":checkbox").prop("checked")) {
                        RowOutEditMode(tr);
//                        tr.children().each(function () {
//                            var td = $(this);
//                            if (td.attr("edit") == "true") {
//                                var inp = td.children(":first");
//                                var inp_value = inp.val();
//                                td.text(inp_value);
//                            }
//                        })
                    }
                })
            }else {
                //进入编辑模式
                $(ths).text("退出编辑模式");
                $(ths).addClass("editing");
                $(tb).children().each(function(){
                    //$(this)循环每一个tr
                    //查找tr下面的checkbox是否被选中
                    var tr = $(this);
                    var isChecked = $(this).find(":checkbox").prop("checked");
                    if(isChecked == true){
                        RowIntoEditMode(tr);
                        //进入编辑状态,循环每一个可以编辑的td
//                        tr.children().each(function(){
//                            var td = $(this);
//                            if(td.attr("edit") == "true"){
//                                var text = td.text();
//                                var temp = "<input type='text' value='" + text + "'/>";
//                                td.html(temp);
//                            }
//                        })
                    }
                })
            }
        }

        function RowIntoEditMode(tr){
            tr.children().each(function(){
                var td = $(this);
                if(td.attr("edit") == "true"){
                    //默认所有更改为input,自定义select表示修改的是下拉框
                    if (td.attr("edit-type") == "select") {
                        //无论是dom还是js引用全局变量其实就是window的变量:比如调用alert(123)
                        //还可以这样调用window.["alert"](123) 或者 window.alert(123)
                        var all_values = window[td.attr("global-key")]; //为了区分不同的下拉框业务和状态 自定义属性
                        var select_val = td.attr("select-val");
                        select_val = parseInt(select_val);
                        var options = "";//有多个下拉框用字符串拼接
                        $.each(all_values, function (index, value) {
                           if(select_val == value.id){
                                options += "<option selected='selected'>" + value.text + "</option>";
                           }else{
                                options += "<option>" + value.text + "</option>";
                            }
                        });//拼接options
                        var temp = "<select onchange='MultiChange(this)'>" + options + "</select>";//拼接最终的select
                        td.html(temp);//修改
                    }else{
                        var text = td.text();
                        var temp = "<input type='text' value='" + text + "'/>";
                        td.html(temp);
                    }
                }
            })
        }

        function RowOutEditMode(tr) {
            //将相同的代码块写成函数
            tr.children().each(function(){
                var td = $(this);
                if(td.attr("edit") == "true"){
                    var inp = td.children(":first");
                    var inp_value = inp.val();
                    td.text(inp_value);
                }
            })
        }
    </script>
</body>
</html>
edit_row

html代码:

    <div style="padding: 20px">
        <input type="button" onclick="CheckAll('#edit_mode', '#tb1');" value="全选" />
        <input type="button" onclick="CheckReverse('#edit_mode', '#tb1');" value="反选" />
        <input type="button" onclick="CheckCancel('#edit_mode', '#tb1');" value="取消" />

        <a id="edit_mode" class="edit-mode" href="javascript:void(0);" onclick="EditMode(this, '#tb1');" >进入编辑模式</a>

    </div>
    <table border="1">
        <thead>
        <tr>
            <th>选择</th>
            <th>主机名</th>
            <th>端口</th>
            <th>业务</th>
            <th>状态</th>
        </tr>
        </thead>
        <tbody id="tb1">
            <tr>
                <td><input type="checkbox" /></td>
                <td edit="true">v1</td>
                <td>v11</td>
                <td edit="true" edit-type="select" select-val="1" global-key="BUSINESS">车上会</td>
                <td edit="true" edit-type="select" select-val="1" global-key="STATUS">在线</td>
            </tr>
            <tr>
                <td><input type="checkbox" /></td>
                <td edit="true">v11</td>
                <td>v11</td>
                <td edit="true" edit-type="select" select-val="2" global-key="BUSINESS">二手车</td>
                <td edit="true" edit-type="select" select-val="2" global-key="STATUS">下线</td>
            </tr>
            <tr>
                <td><input type="checkbox" /></td>
                <td edit="true">v111</td>
                <td>v11</td>
                <td edit="true" edit-type="select" select-val="3" global-key="BUSINESS">大保健</td>
                <td edit="true" edit-type="select" select-val="2" global-key="STATUS">下线</td>
            </tr>
        </tbody>
    </table>
View Code

jQuery代码:

<script type="text/javascript" src="jquery-2.2.3.js"></script>
    <script>

        STATUS = [
            {'id': 1, 'text': "在线"},
            {'id': 2, 'text': "下线"}
        ];
        BUSINESS = [
            {'id': 1, 'text': "车上会"},
            {'id': 2, 'text': "二手车"},
            {'id': 3, 'text': "大保健"}
        ];
        //console.log(STATUS);
        //console.log(window["STATUS"]);

        $(function(){
            $("#tb1").find(":checkbox").click(function(){
                var tr = $(this).parent().parent();
                var isEditing = $("#edit_mode").hasClass("editing");
                //进入编辑
                if(isEditing){
                    //判断是否已经选中
                    //先执行默认的事件
                    if($(this).prop("checked")){
                        //当前行进入编辑状态
                        RowIntoEditMode(tr);
                    }else{
                        //当前行退出编辑状态
                        RowOutEditMode(tr);
                    }
                }
            });
        });

        globalCtrlKeyPress = false;

        window.onkeydown = function(event){
            console.log(event.keyCode);
            if(event && event.keyCode==17){
                window.globalCtrlKeyPress = true;
            }else{
                window.globalCtrlKeyPress = false;
            }
        };

        //如果任意键放开执行function
        window.onkeyup = function (event) { //这里需要传入evnent
       //如果ctrl键up
            if(event && event.keyCode == 17 ){
            //设置globalCtrlKeyPress为false
            window.globalCtrlKeyPress = false;
            }
        };    

        function MultiChange(ths){
            //检测是否按下ctrl键
            if(window.globalCtrlKeyPress == true){
                //td所在的tr中的索引位置目的是修改该列为统一的值
                var index = $(ths).parent().index();
                var value = $(ths).val();
                $(ths).parent().parent().nextAll().find("td input[type='checkbox']:checked").each(function(){
                    $(this).parent().parent().children().eq(index).children().val(value);
                })
            }
        }

        function CheckAll(mode,tb){
            //选中checkbox
            //如果已经进入编辑模式,让选中行进入编辑模式
            //tb = #tb1
            $(tb).children().each(function(){
                //$(this)循环每一个tr
                //查找tr下面的checkbox是否被选中
                var tr = $(this);
                var isChecked = $(this).find(":checkbox").prop("checked");
                if(isChecked == true){
                }else{
                    //复选框未选中,选中
                    $(this).find(":checkbox").prop("checked",true);
                    //查看是否进入编辑状态
                    var isEditing = $(mode).hasClass("editing");
                    //进入编辑
                    if(isEditing){
                        //进入编辑状态,循环每一个可以编辑的td
                        RowIntoEditMode(tr);
                    }
                }
            })
        }

        function CheckCancel(mode,tb){
            // 取消选中checkebox
            //如果已经进入编辑模式,行退出编辑状态
            $(tb).children().each(function(){
                var tr = $(this);
                if(tr.find(":checkbox").prop("checked")){
                    //移除选中
                    tr.find(":checkbox").prop("checked",false);
                    var isEditing = $(mode).hasClass("editing");
                    if(isEditing == true){
                        //当前行,退出编辑状态
                        RowOutEditMode(tr);
                    }
                }
            })
        }

        function CheckReverse(mode,tb){
            //是否进入编辑模式
            if($(mode).hasClass("editing")){
                $(tb).children().each(function(){
                    //遍历所有tr
                    var tr = $(this);
                    //找到tr的第一个td 复选框,判断是否被选中
                    var check_box = tr.children().first().find(":checkbox");
                    if(check_box.prop("checked")){
                        check_box.prop("checked", false); //选中,设置为未选中
                        //当前行,退出编辑状态
                        RowOutEditMode(tr);
                    }
                    else{
                        check_box.prop("checked",true);
                        //当前行,进入编辑状态
                        RowIntoEditMode(tr);
                    }
                });
            }else{
                //未进入编辑状态,只需要修改复选框的状态即可
                $(tb).children().each(function(){
                    var tr=$(this);
                    var check_box = tr.children().first().find(":checkbox");
                    if(check_box.prop('checked')){
                        check_box.prop("checked",false);
                    }else{
                        check_box.prop("checked",true);
                    }
                });
            }
        }

        function EditMode(ths,tb){
            var isediting = $(ths).hasClass("editing");
            if(isediting){
                $(ths).text("进入编辑模式");
                $(ths).removeClass("editing");
                $(tb).children().each(function() {
                    //$(this)循环每一个tr
                    //查找tr下面的checkbox是否被选中
                    var tr = $(this);
                    if (tr.find(":checkbox").prop("checked")) {
                        RowOutEditMode(tr);
                    }
                })
            }else {
                //进入编辑模式
                $(ths).text("退出编辑模式");
                $(ths).addClass("editing");
                $(tb).children().each(function(){
                    //$(this)循环每一个tr
                    //查找tr下面的checkbox是否被选中
                    var tr = $(this);
                    var isChecked = $(this).find(":checkbox").prop("checked");
                    if(isChecked == true){
                        RowIntoEditMode(tr);//进入编辑状态,循环每一个可以编辑的td
                    }
                })
            }
        }

        function RowIntoEditMode(tr){
            tr.children().each(function(){
                var td = $(this);
                if(td.attr("edit") == "true"){
                    //默认所有更改为input,自定义select表示修改的是下拉框
                    if (td.attr("edit-type") == "select") {
                        //无论是dom还是js引用全局变量其实就是window的变量:比如调用alert(123)
                        //还可以这样调用window.["alert"](123) 或者 window.alert(123)
                        var all_values = window[td.attr("global-key")]; //为了区分不同的下拉框业务和状态 自定义属性
                        var select_val = td.attr("select-val");
                        select_val = parseInt(select_val);
                        var options = "";//有多个下拉框用字符串拼接
                        $.each(all_values, function (index, value) {
                           if(select_val == value.id){
                                options += "<option selected='selected'>" + value.text + "</option>";
                           }else{
                                options += "<option>" + value.text + "</option>";
                            }
                        });//拼接options
                        var temp = "<select onchange='MultiChange(this)'>" + options + "</select>";//拼接最终的select
                        td.html(temp);//修改
                    }else{
                        var text = td.text();
                        var temp = "<input type='text' value='" + text + "'/>";
                        td.html(temp);
                    }
                }
            })
        }

        function RowOutEditMode(tr) {
            //将相同的代码块写成函数
            tr.children().each(function(){
                var td = $(this);
                if(td.attr("edit") == "true"){
                    var inp = td.children(":first");
                    var inp_value = inp.val();
                    td.text(inp_value);
                }
            })
        }
    </script>                

效果:

咱们首先处理几个按钮和编辑模式,对于全选有一个需要注意的,需要判断当前checkbox是否被选,避免在进入编辑模式后重复选中,内容被覆盖为空。取消跟全选差不多,遍历tr标签,

移除被选中的复选框,同时进入编辑模式的需要退出。反选首先需要判断是否处理编辑模式,编辑模式下反选,选中被取消,退出编辑模式;未选中被选中,进入编辑模式;非编辑模式只需要更改复选框。

编辑模式咱们通过class来实现。对于进入编辑行和退出编辑行状态有很多重复的代码写成两个函数RowOutEditMode和RowIntoEditMode;默认修改的都是input type=text,

有一些下拉框的形式修改,通过自定义属性编辑模式,  利用全局变量定义数组,自定义全局属性可以区分多个下拉框修改项(比如业务和主机状态的修改),还可以定义是否进入编辑模式,

默认选中项等,你可以根据自己的需求自定义属性(类似与python中的flag,非常的有用!!!)还有一些提高逼格的批量修改功能可以参看上面的代码和注释。

更多详细见:http://www.cnblogs.com/wupeiqi/articles/5369773.html

jQuery扩展

jQuery已经为我们提供了那么多的方法,但是有时候我们想要自己定义一些方法怎么办?jQuery还提供了两个方法:

jQuery.fn.extend(object)

jQuery.extend(object)

jQuery 代码:

jQuery.extend({
  min: function(a, b) { return a < b ? a : b; },
  max: function(a, b) { return a > b ? a : b; }
});

一般使用下面的方式:

(function(arg){
  arg.extend({
    min: function(a, b) { return a < b ? a : b; },
    max: function(a, b) { return a > b ? a : b; }
  });
})(jQuery);

结果:

jQuery.min(2,3); // => 2   // jQuery =$    $.min(2,3);
jQuery.max(4,5); // => 5          

jQuery 代码:

jQuery.fn.extend({
  check: function() {
    return this.each(function() { this.checked = true; });
  },
  uncheck: function() {
    return this.each(function() { this.checked = false; });
  }
});

结果:

$("input[type=checkbox]").check();
$("input[type=radio]").uncheck();

jQuery.fn.extend(object) 与 jQuery.extend(object)的区别在与 fn的定义可以应用在selector上。

更多详细的内容请见:http://www.php100.com/manual/jquery/

form表单验证(登录注册)

(function(jq){

    function ErrorMessage(container,msg){
        $error = container.find("label[class='input-error']");
        if($error.length>0){
            $error.text(msg);
        }else{
            var temp = "<label class='input-error'>"+msg+"</label>";
            container.append(temp);
        }
        
    }
    
    function EmptyError(container){
        $error = container.find("label[class='input-error']");
        if($error.length>0){
            $error.remove();
        }
    }

    jq.extend({
        'CheckAll':function(targetcontainer){
            $(targetcontainer).find(':checkbox').attr('checked',true);
        },
        'UnCheckAll':function(targetcontainer){
            $(targetcontainer).find(':checkbox').attr('checked',false);
        },    
        'ReverseCheck':function(targetcontainer){
            $(targetcontainer).find(':checkbox').each(function(){
                var check = $(this).attr('checked');
                console.log(check);
                if(check){
                    $(this).attr('checked',false);
                }else{
                    $(this).attr('checked',true);
                }
            })
        },
        'Hide':function(target){
            $(target).addClass('hide');
        },
        'Show':function(target){
            $(target).removeClass('hide');
        },
        'register':function(form,summaryStatusId){
            $(form).find(':submit').click(function(){
                var flag = true;
                
                
                $(form).find(':text,:password').each(function(){
                    var name = $(this).attr('name');
                    var label = $(this).attr('label');
                    var val = $(this).val();
                    var $parent = $(this).parent();
                    
                    //<label class='input-error'>用户名长度只能在4-20位字符之间</label>
                    //<label class='input-error'>用户名只能由中文、英文、数字及"-"、"_"组成</label>
                    
                    var required = $(this).attr('require');
                    if(required){
                        if(!val || val.trim() == ''){
                            flag = false;
                            ErrorMessage($parent,label+'不能为空.');
                            return false;
                        }
                    }
                    
                    var confirm_to = $(this).attr('confirm-to');
                    if(confirm_to){
                        var $original = $(form).find("input[name='"+confirm_to+"']");
                        if($original.val().trim()!=val.trim()){
                            flag = false;
                            ErrorMessage($parent,'两次密码输入不一致.');
                            return false;
                        }
                    }
                    
                    var number = $(this).attr('number');
                    if(number){
                        if(!$.isNumeric(number)){
                            flag = false;
                            ErrorMessage($parent,label+'必须为数字.');
                            return false;
                        }
                    }
                    
                    var mobile = $(this).attr('mobile');
                    if(mobile){
                        var reg = /^1[3|5|8]\d{9}$/;
                        if(!reg.test(val)){
                            flag = false;
                            ErrorMessage($parent,label+'格式错误.');
                            return false;
                        }
                    }
                    
                    var min = $(this).attr('min-len');
                    if(min){
                        var len = parseInt(min)
                        if(val.length<len){
                            flag = false;
                            ErrorMessage($parent,label+'最小长度为'+min+'.');
                            return false;
                        }
                    }
                    
                    var max = $(this).attr('max-len');
                    if(max){
                        var len = parseInt(max)
                        if(val.length>len){
                            flag = false;
                            ErrorMessage($parent,label+'最大长度为'+max+'.');
                            return false;
                        }
                    }
                    
                    var range = $(this).attr('range');
                    if(range){
                        var len = range.split('-');
                        if(val.length<parseInt(len[0])||val.length>parseInt(len[1])){
                            flag = false;
                            ErrorMessage($parent,label+'长度只能在'+len[0]+'-'+len[1]+'位字符之间.');
                            return false;
                        }
                    }
                    
                    var field = $(this).attr('Field');
                    if(field=='string'){
                        var reg = /^\w+$/;
                        if(!reg.test(val)){
                            flag = false;
                            ErrorMessage($parent,label+'只能由英文、数字及"_"组成.');
                            return false;
                        }
                    }
                    EmptyError($parent);
                });
                
                
                var check = $("#protocol").prop('checked');
                
                if(!check){
                    flag = false;
                    try{
                        ErrorMessage($("#protocol").parent().parent(),'请阅读用户注册协议.');
                    }catch(e){
                        flag = false;
                    }
                }else{
                    EmptyError($("#protocol").parent().parent());
                }
                
                return flag;
            });
        },
        'login':function(form,summaryStatusId){
            $(form).find(':submit').click(function(){
                var flag = true;
                
                
                $(form).find(':text,:password').each(function(){
                    var name = $(this).attr('name');
                    var label = $(this).attr('label');
                    var val = $(this).val();
                    var $parent = $(this).parent();
                    
                    var required = $(this).attr('require');
                    if(required){
                        if(!val || val.trim() == ''){
                            flag = false;
                            ErrorMessage($parent,label+'不能为空.');
                            return false;
                        }
                    }

                    EmptyError($parent);
                });
                
                return flag;
            });
        },
    });
    

})(jQuery)
jq-extend
                <form id='Form' action='/account/login' method='POST'>
                    
                    <div class='group mt10'>
                        <label class='tip'><span class="red">*</span>用户名:</label>
                        <input type='text' require='true' label='用户名' Field='string' range='4-40' name='username' />
                        <i class='i-name'></i>
                    </div>
                  
                    <div class='group'>
                        <label class='tip'><span class="red">*</span>密码:</label>
                        <input  type='password' require='true'  label='密码' min-len='6' name='pwd' />
                        <i class='i-pwd'></i>
                    </div>
                   
                    <div class='group'>
                        <label class='tip'><span class="red">*</span>验证码:</label>
                        <input  type='text' require='true' label='验证码' style='width:80px;' name='checkcode' />
                        <a style='width:125px;display:inline-block;'><img class='checkcode' onclick='ChangeCode();' id='imgCode' src='/account/check' /></a>
                    </div>
                    <div class='group font12 mb0'>
                        <label class='tip'></label>
                        <label style='width:246px;display: inline-block;'>
                            <input id='protocol' name='protocol' type='checkbox' checked='checked' />
                            <span>自动登录</span>
                            <span class='ml10'><a href='#'>忘记密码?</a></span>
                        </label>
                    </div>
                    <div class='group mt0'>
                        <label class='tip'></label>
                        <input type='submit' class='submit' value='登    录' />
                    </div>
                </form>
login
                    <div>
                        <h1 class='mb20'>注册新用户</h1>
                        <form id='Form' method='POST' action='/account/register'>
                            <div class='group'>
                                <label class='tip'><span class="red">*</span>用户名:</label>
                                <input type='text' require='true' label='用户名' Field='string' range='4-40' name='username' />
                                <i class='i-name'></i>
                                
                            </div>
                            <div class='group'>
                                <label class='tip'><span class="red">*</span>手机号:</label>
                                <input  type='text' require='true' label='手机号' mobile='true' name='telphone' />
                                <i class='i-phone'></i>
                            </div>
                            <div class='group'>
                                <label class='tip'><span class="red">*</span>登录密码:</label>
                                <input  type='password' require='true'  label='登录密码' min-len='6' name='pwd' />
                                <i class='i-pwd'></i>
                            </div>
                            <div class='group'>
                                <label class='tip'><span class="red">*</span>确认密码:</label>
                                <input  type='password' require='true' label='确认密码' confirm-to='pwd' name='confirmpwd' />
                                <i class='i-pwd'></i>
                            </div>
                            <div class='group'>
                                <label class='tip'><span class="red">*</span>验证码:</label>
                                <input  type='text' require='true' label='验证码' style='width:80px;' name='checkcode' />
                                <a style='width:125px;display:inline-block;'><img class='checkcode' onclick='ChangeCode();' id='imgCode' src='/account/check' /></a>
                            </div>
                            <div class='group font12'>
                                <label class='tip'></label>
                                <label style='width:246px;display: inline-block;'>
                                    <input id='protocol' name='protocol' type='checkbox' checked='checked' /><span>我已阅读并同意<a href='#'>《用户注册协议》</a></span>
                                </label>
                            </div>
                            
                            <div class='group'>
                                <label class='tip'></label>
                                <input type='submit' class='submit' value='同意以上协议并注册' />
                            </div>
                        </form>
                    </div>
                </div>
register

还有两个比较不错的扩展连接:

-- parsleyjs
http://parsleyjs.org/
-- jQuery Validate
http://jqueryvalidation.org/
posted @ 2016-04-18 23:18  ko_ka24  阅读(284)  评论(0)    收藏  举报