jQuery基础

jQuery基础

jQuery概述 & 对象

jQuery寻找元素(选择器&筛选器)

操作元素(属性, CSS, 文档处理)

事件

动画效果

扩展方法(插件机制)

实例练习

 


jQuery概述

JQuery是一个兼容多浏览器的javascript库, 核心理念是write less, do more(写得更少, 做得更多). 对javascript进行了封装, 使开发更加便捷, 并且在兼容性方面十分优秀.

jQuery对象

jQuery 对象就是通过jQuery包装DOM对象后产生的对象. jQuery 对象是 jQuery 独有的如果一个对象是 jQuery 对象那么它就可以使用 jQuery 里的方法: $(“#test”).html();

$("#test").html()    
// 意思是指:获取ID为test的元素内的html代码. 其中html()是jQuery里的方法 

// 这段代码等同于用DOM实现代码: document.getElementById(" test ").innerHTML; 

// 虽然jQuery对象是包装DOM对象后产生的, 但是jQuery无法使用DOM对象的任何方法, 同理DOM对象也不能使用jQuery里的方法.乱使用会报错.

// 约定:如果获取的是jQuery对象, 那么要在变量前面加上$. 

var $variable = jQuery 对象
var variable = DOM 对象

$variable[0]:jquery对象转为dom对象      $("#msg").html(); $("#msg")[0].innerHTML

jQuery的基础语法:$(selector).action()

 


寻找元素(选择器和筛选器) 

选择器

基本选择器    

$("*")  
$("#id")   
$(".class")  
$("element")  
$(".class, p, div")

层级选择器   

$(".outer div")  
$(".outer>div")   
$(".outer+div")  
$(".outer~div")

基本筛选器   

$("li:first")  
$("li:eq(2)")    // 等于
$("li:even")     
$("li:gt(1)")    // 大于
$("li:lt(1)")    // 小于
$("li:last")  

属性选择器     

$('[id="div1"]')   
$('["lala="haha"][id]')

表单选择器  

$("[type='text']")   等同于   $(":text")         

// 注意只适用于input标签: $("input:checked")

 

筛选器

过滤筛选器

$("li").eq(2)  
$("li").first()  
$("ul li").hasclass("test")

查找筛选器

 $("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()
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery-3.3.1.js"></script>
</head>
<body>
    <div class="div1">hello 1
        <div class="div7">hello 8</div>
        <div class="div2">hello 2
            <div class="div3">hello 3</div>
        </div>
        <div class="div3">hello 4</div>
        <div class="div4">hello 5</div>
        <div class="div5">hello 6
            <div class="div9">hello 9</div>
        </div>
        <div class="div6">hello 7</div>
    </div>
    <p>hihihihihi</p>
</body>

<script>
    //children - 只找子代元素, find - 找所有后代元素
    // $(".div1").children(".div3").css('color','red');
    // $(".div1").find(".div3").css('color','red');

    //next - 与它同级的下个元素, nextAll - 与它同级的下面的所有元素, nextUntil - 与它同级的下面到until之前的元素, 不包括until的元素
    // $(".div2").next().css('color','red');
    // $(".div2").nextAll().css('color','red');
    // $(".div2").nextUntil(".div6").css('color','red');

    //与next相反
    // $(".div2").prev().css('color','red');
    // $(".div3").prevAll().css('color','red');
    // $(".div2").prevUntil(".div6").css('color','red');


    // $(".div2").parent().css('color','red');  //div1内全变红
    // $(".div2").parents().css('color','red');  //父级的父级, 全部变红
    // $(".div3").parentsUntil(".div1").css('color','red');  //div2内全变红


    $(".div2").siblings().css('color','red');  //hello1,2,3没变, 其他都变
</script>
</html>
View Code

实例: 左侧菜单

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>left_menu</title>
    <style>
          .menu{
              height: 500px;
              width: 30%;
              background-color: lemonchiffon;
              float: left;
          }
          .content{
              height: 500px;
              width: 70%;
              background-color: salmon;
              float: left;
          }
         .title{
             border: #c0cddf solid 1px;
             line-height: 50px;
             background-color: #425a66;
             color: skyblue;}


         .hide{
             display: none;
         }
    </style>

</head>
<body>

<div class="outer">
    <div class="menu">
        <div class="item">
            <div class="title" onclick="show(this)">菜单一</div>
            <div class="con">
                <div>111</div>
                <div>111</div>
                <div>111</div>
            </div>
        </div>
        <div class="item">
            <div class="title" onclick="show(this)">菜单二</div>
            <div class="con hide">
                <div>111</div>
                <div>111</div>
                <div>111</div>
            </div>
        </div>
        <div class="item">
            <div class="title" onclick="show(this)">菜单三</div>
            <div class="con hide">
                <div>111</div>
                <div>111</div>
                <div>111</div>
            </div>
        </div>

    </div>
    <div class="content"></div>
</div>

<script src="jquery-3.3.1.js"></script>
<script>
    // 方式一:
    $(".item .title").click(function () {
        // $(this).next().removeClass("hide").parent().siblings().children(".con").addClass("hide");

        $(this).next().removeClass("hide");  //和con并列的hide会被remove
        $(this).parent().siblings().children(".con").addClass("hide");
    })

    // 方式二: 在class="title"后面onclick时间
    // function show(a) {
    //     $(a).next().removeClass("hide");
    //     $(a).parent().siblings().children(".con").addClass("hide");
    // }
</script>
</body>
</html>
View Code

实例: tab菜单

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>tab</title>
    <script src="jquery-3.3.1.js"></script>
    <script>
           function tab(self){
               var index=$(self).attr("xxx");
               $("#"+index).removeClass("hide").siblings().addClass("hide");
               $(self).addClass("current").siblings().removeClass("current");
           }
    </script>
    <style>
        *{
            margin: 0px;
            padding: 0px;
        }
        .tab_outer{
            margin: 0px auto;
            width: 60%;
        }
        .menu{
            background-color: #cccccc;
            /*border: 1px solid red;*/
            line-height: 40px;
        }
        .menu li{
            display: inline-block;
        }
        .menu a{
            border-right: 1px solid red;
            padding: 11px;
        }
        .content{
            background-color: tan;
            border: 1px solid green;
            height: 300px;
        }
        .hide{
            display: none;
        }

        .current{
            background-color: darkgray;
            color: yellow;
            border-top: solid 2px rebeccapurple;
        }
    </style>
</head>
<body>
      <div class="tab_outer">
          <ul class="menu">
              <li xxx="c1" class="current" onclick="tab(this);">菜单一</li>
              <li xxx="c2" onclick="tab(this);">菜单二</li>
              <li xxx="c3" onclick="tab(this);">菜单三</li>
          </ul>
          <div class="content">
              <div id="c1">内容一</div>
              <div id="c2" class="hide">内容二</div>
              <div id="c3" class="hide">内容三</div>
          </div>
      </div>
</body>
</html>
View Code
body {
    margin: 0 auto;
    font-family: Arial;
    _font-family: 宋体,Arial;
    font-size: 12px;
}
body, dl, dt, dd, ul, ol, li, h1, h2, h3, h4, h5, h6, pre, code, form, fieldset, legend, input, button, textarea, p, blockquote, th, td, figure, div {
    margin: 0;
    padding: 0;
}

ol, ul, li {
    list-style: none;
}
a{
    cursor:pointer;
    text-decoration:none;
}
/*a:hover{
    color: #F60 !important;
    text-decoration: underline;
}*/
img{
    border:none;
    border-width:0px;
}
table{
    border-collapse: collapse;
    border-spacing: 0;
}

.red{
    color: #c00!important;
}
.m8{
    margin:8px;
}
.mt10{
    margin-top:10px;
}
.mt20{
    margin-top:20px;
}
.mr5{
    margin-right:5px;
}
.ml5{
    margin-left:5px;
}

.ml10{
    margin-left:10px;
}

.mb10{
    margin-bottom:10px;
}
.pt18{
    padding-top:18px;
}
.pt20{
    padding-top:20px;
}
.pb20{
    padding-bottom:20px;
}
.nbr{
    border-right:0px;
}
.font12{
    font-size:12px;
}
.font14{
    font-size:14px;
}
.font16{
    font-size:16px;
}
.bold{
    font-weight:bold;
}
.left{
    float:left;
}
.right{
    float:right;
}
.hide{
    display:none;
}
.show{
     display:table;
}
.clearfix{
    clear:both;
}
.clearfix:after {
    content: ".";
    display: block;
    height: 0;
    clear: both;
    visibility: hidden;
}
* html .clearfix {zoom: 1;}

.container{
    width:1190px;
    margin-left:auto;
    margin-right:auto;

}

.group-box-1 .title{
    height: 33px;
    line-height: 33px;
    border: 1px solid #DDD;
    background: #f5f5f5;
    padding-top: 0;
    padding-left: 0;

}
.group-box-1 .title .title-font{
    display: inline-block;
    font-size: 14px;
    font-family: 'Microsoft Yahei','SimHei';
    font-weight: bold;
    color: #333;
    padding-left: 10px;
}
.group-box-1 .body {
    border: 1px solid #e4e4e4;
    border-top: none;
}

.tab-menu-box1 {
    border: 1px solid #ddd;
    margin-bottom: 20px;
}

.tab-menu-box1 .menu {
    line-height: 33px;
    height: 33px;
    background-color: #f5f5f5;
}

.tab-menu-box1 .content {
    min-height: 100px;
    border-top: 1px solid #ddd;
    background-color: white;
}

.tab-menu-box1 .menu ul {
    padding: 0;
    margin: 0;
    list-style: none;
    /*position: absolute;*/
}

.tab-menu-box1 .menu ul li {
    position: relative;
    float: left;
    font-size: 14px;
    font-family: 'Microsoft Yahei','SimHei';
    text-align: center;
    font-size: 14px;
    font-weight: bold;
    border-right: 1px solid #ddd;
    padding: 0 18px;
    cursor: pointer;
}

.tab-menu-box1 .menu ul li:hover {
    color: #c9033b;
}

.tab-menu-box1 .menu .more {
    float: right;
    font-size: 12px;
    padding-right: 10px;
    font-family: "宋体";
    color: #666;
    text-decoration: none;
}

.tab-menu-box1 .menu a:hover {
    color: #f60 !important;
    text-decoration: underline;
}

.tab-menu-box1 .menu .current {
    margin-top: -1px;
    color: #c9033b;
    background: #fff;
    height: 33px;
    border-top: 2px solid #c9033b;
    z-index: 10;
}

.tab-menu-box-2 .float-title {
    display: none;
    top: 0px;
    position: fixed;
    z-index: 50;
}

.tab-menu-box-2 .title {
    width: 890px;
    border-bottom: 2px solid #b20101;
    border-left: 1px solid #e1e1e1;
    clear: both;
    height: 32px;
}

.tab-menu-box-2 .title a {
    float: left;
    width: 107px;
    height: 31px;
    line-height: 31px;
    font-size: 14px;
    font-weight: bold;
    text-align: center;
    border-top: 1px solid #e1e1e1;
    border-right: 1px solid #e1e1e1;
    background: url(/Content/images/bg4.png?3) 0 -308px repeat-x;
    text-decoration: none;
    color: #333;
    cursor: pointer;
}

.tab-menu-box-2 .title a:hover {
    background-position: -26px -271px;
    text-decoration: none;
    color: #fff;
}

.tab-menu-box-2 .content {
    min-height: 100px;
    background-color: white;
}


.tab-menu-box3 {
    border: 1px solid #ddd;
}

.tab-menu-box3 .menu {
    line-height: 33px;
    height: 33px;
    background-color: #f5f5f5;
}

.tab-menu-box3 .content {
    height: 214px;
    border-top: 1px solid #ddd;
    background-color: white;
}

.tab-menu-box3 .menu ul {
    padding: 0;
    margin: 0;
    list-style: none;
    /*position: absolute;*/
}

.tab-menu-box3 .menu ul li {
    position: relative;
    float: left;
    font-size: 14px;
    font-family: 'Microsoft Yahei','SimHei';
    text-align: center;
    font-size: 14px;
    width:50%;
    cursor: pointer;
}

.tab-menu-box3 .menu ul li:hover {
    color: #c9033b;
}

.tab-menu-box3 .menu .more {
    float: right;
    font-size: 12px;
    padding-right: 10px;
    font-family: "宋体";
    color: #666;
    text-decoration: none;
}

.tab-menu-box3 .menu a:hover {
    color: #f60 !important;
    text-decoration: underline;
    font-weight: bold;
}

.tab-menu-box3 .menu .current {

    margin-top: -1px;
    color: #c9033b;
    background: #fff;
    height: 33px;
    border-top: 2px solid #c9033b;
    z-index: 10;
    font-weight: bold;

}
美化版_css
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <link href="tab.css" rel="stylesheet" />
</head>

<body>
    <div class='container'>
        <div class='tab-menu-box1'>
            <div class='menu'>
                <ul id='tab-menu-title'>
                    <li class='current' content-to='1'>价格趋势</li>
                    <li content-to='2'>市场分布</li>
                    <li content-to='3'>其他</li>
                </ul>
            </div>

            <div id='tab-menu-body' class='content'>
                <div content='1'>content1</div>
                <div content='2' class='hide'>content2</div>
                <div content='3' class='hide'>content3</div>
            </div>
        </div>
    </div>
    <script src="jquery-3.3.1.js"></script>
    <script type='text/javascript'>
    $(function(){
        ChangeTab('#tab-menu-title', '#tab-menu-body');
    })
    function ChangeTab(title, body) {
            $(title).children().bind("click", function () {
                $menu = $(this);
                $content = $(body).find('div[content="' + $(this).attr("content-to") + '"]');
                $menu.addClass('current').siblings().removeClass('current');
                $content.removeClass('hide').siblings().addClass('hide');
            });
        }
    </script>
</body>
</html>
美化版_html

 


操作元素(属性,css,文档处理)

1. 属性操作

-------------------------- 属性
$("").attr();
$("").removeAttr();
$("").prop();
$("").removeProp();
-------------------------- CSS类
$("").addClass(class|fn)
$("").removeClass([class|fn])
-------------------------- HTML代码/文本/值
$("").html([val|fn])
$("").text([val|fn])
$("").val([val|fn|arr])
---------------------------
$("").css("color","red")

注意:

<input id="chk1" type="checkbox" />是否可见
<input id="chk2" type="checkbox" checked="checked" />是否可见
<script>
    console.log($("#chk1").prop("checked"));//false
    console.log($("#chk2").prop("checked"));//true
    console.log($("#chk1").attr("checked"));//undefined
    console.log($("#chk2").attr("checked"));//checked
</script>

prop()函数的结果:
      1.如果有相应的属性, 返回true
      2.如果没有相应的属性, 返回false
attr()函数的结果:
      1.如果有相应的属性, 返回指定属性值
      2.如果没有相应的属性, 返回值是undefined

//对于HTML元素本身就带有的固有属性,在处理时,使用prop方法.
//对于HTML元素我们自己自定义的DOM属性,在处理时,使用attr方法.
//像checkbox,radio和select这样的元素,选中属性对应“checked”和“selected”,这些也属于固有属性,因此需要使用prop方法去操作才能获得正确的结果.

// 对于prop
// $("#chk1").prop("checked","") 和
// $("#chk1").prop("checked","check") 可以取消选择和选择
// 用attr则做不到
attr和prop

jQuery循环的两种方式:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
     <table border="1">
         <tr>
             <td><input type="checkbox"></td>
             <td>111</td>
         </tr>
         <tr>
             <td><input type="checkbox"></td>
             <td>222</td>
         </tr>
         <tr>
             <td><input type="checkbox"></td>
             <td>333</td>
         </tr>
         <tr>
             <td><input type="checkbox"></td>
             <td>444</td>
         </tr>
     </table>

<script src="jquery-3.3.1.js"></script>
<script>
    // jquery循环的两种方式
    // 方式一
    li=[10,20,30,40]
    dic={name:"charon",sex:"male"}
    $.each(li,function(i,x){
        console.log(i,x)
    })

    // 方式二
    $("tr").each(function(){
        console.log($(this).html())
    })
</script>
</body>
</html>
View Code

实例: 全反选

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery-3.3.1.js"></script>
    <script>
        function selectall(){
            $("table :checkbox").prop("checked",true)
        }
        function cancel(){
            $("table :checkbox").prop("checked",false)
        }
        function reverse(){
            $("table :checkbox").each(function(){
                //方式一:
                $(this).prop("checked",!$(this).prop("checked"));
                // // 方式二:
                // if ($(this).prop("checked")){
                //     $(this).prop("checked",false)
                // }
                // else {
                //     $(this).prop("checked",true)
                // }
            });
        }

    </script>
</head>
<body>
    <button onclick="selectall();">全选</button>
    <button onclick="cancel();">取消</button>
    <button onclick="reverse();">反选</button>

    <table border="1">
        <tr>
            <td><input type="checkbox"></td>
            <td>111</td>
        </tr>
        <tr>
            <td><input type="checkbox"></td>
            <td>222</td>
        </tr>
        <tr>
            <td><input type="checkbox"></td>
            <td>333</td>
        </tr>
        <tr>
            <td><input type="checkbox"></td>
            <td>444</td>
        </tr>
    </table>
</body>
</html>
View Code

实例: 模态对话框

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .back{
            background-color: rebeccapurple;
            height: 2000px;
        }

        .shade{
            position: fixed;
            top: 0;
            bottom: 0;
            left:0;
            right: 0;
            background-color: coral;
            opacity: 0.4;
        }

        .hide{
            display: none;
        }

        .models{
            position: fixed;
            top: 50%;
            left: 50%;
            margin-left: -100px;
            margin-top: -100px;
            height: 200px;
            width: 200px;
            background-color: gold;

        }
    </style>
</head>
<body>
<div class="back">
    <input id="ID1" type="button" value="click" onclick="action1(this)">
</div>

<div class="shade hide"></div>
<div class="models hide">
    <input id="ID2" type="button" value="cancel" onclick="action2(this)">
</div>


<script src="jquery-3.3.1.js"></script>
<script>
    function action1(self){
        $(self).parent().siblings().removeClass("hide");

    }
    function action2(self){
        //$(self).parent().parent().children(".models,.shade").addClass("hide")
        $(self).parent().addClass("hide").prev().addClass("hide")
    }
</script>
</body>
</html>
View Code

 

2. 文档处理

//创建一个标签对象
    $("<p>")

//内部插入
    $("").append(content|fn)      ----->$("p").append("<b>Hello</b>");
    $("").appendTo(content)       ----->$("p").appendTo("div");
    $("").prepend(content|fn)     ----->$("p").prepend("<b>Hello</b>");
    $("").prependTo(content)      ----->$("p").prependTo("#foo");

//外部插入
    $("").after(content|fn)       ----->$("p").after("<b>Hello</b>");
    $("").before(content|fn)      ----->$("p").before("<b>Hello</b>");
    $("").insertAfter(content)    ----->$("p").insertAfter("#foo");
    $("").insertBefore(content)   ----->$("p").insertBefore("#foo");

//替换
    $("").replaceWith(content|fn) ----->$("p").replaceWith("<b>Paragraph. </b>");

//删除
    $("").empty()
    $("").remove([expr])

//复制
    $("").clone([Even[,deepEven]])

实例: 复制样式条

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

</head>
<body>
            <div class="outer">
                <div class="item">
                        <input type="button" value="+" onclick="add(this);">
                        <input type="text">
                </div>
            </div>

<script src="jquery-3.3.1.js"></script>
    <script>
            function add(self){
                // 注意: 如果var $clone_obj=$(".outer .item").clone();会一遍二,二变四的增加
                 var $clone_obj=$(self).parent().clone();
                 $clone_obj.children(":button").val("-").attr("onclick","removed(this)");
                 $(self).parent().parent().append($clone_obj);
            }
           function removed(self){
               $(self).parent().remove()
           }
    </script>
</body>
</html>
View Code

 

3. CSS操作

   CSS
        $("").css(name|pro|[,val|fn])
    位置
        $("").offset([coordinates])   // 获取当前标签距离文档顶部的高度
        $("").position()
        $("").scrollTop([val])   //有参数时, 跳转数值位置
        $("").scrollLeft([val])
    尺寸
        $("").height([val|fn])   // 获取当前标签自己的高度
        $("").width([val|fn])
        $("").innerHeight()    // 获取第一个匹配元素内部区域高度(自己高度+padding)
        $("").innerWidth()
        $("").outerHeight([soptions])   //参数为true时, 获取自己高度+padding+border
                        //参数为false时, 获取自己高度+padding+border+margin $("").outerWidth([options])

实例: 返回顶部

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery-3.3.1.js"></script>
    <script>
        window.onscroll=function(){
            var current=$(window).scrollTop();
            console.log(current);
            if (current>100){
                $(".returnTop").removeClass("hide");
            }
            else {
                $(".returnTop").addClass("hide");
            }
        }
        function returnTop(){
            //$(".div1").scrollTop(0);
            $(window).scrollTop(0);
        }
    </script>
    <style>
        body{
            margin: 0px;
        }
        .returnTop{
            height: 60px;
            width: 100px;
            background-color: darkgray;
            position: fixed;
            right: 0;
            bottom: 0;
            color: greenyellow;
            line-height: 60px;
            text-align: center;
        }
        .div1{
            background-color: orchid;
            font-size: 5px;
            overflow: auto;
            width: 500px;
        }
        .div2{
            background-color: darkcyan;
        }
        .div3{
            background-color: aqua;
        }
        .div{
            height: 600px;
        }
        .hide{
            display: none;
        }
    </style>
</head>
<body>
     <div class="div1 div">
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
         <p>hello</p>
     </div>
     <div class="div2 div"></div>
     <div class="div3 div"></div>
     <div class="returnTop" onclick="returnTop();">返回顶部</div>
</body>
</html>
View Code

 


事件

页面载入
  • ready(fn)  // 当DOM载入就绪可以查询及操纵时绑定一个要执行的函数.
    $(document).ready(function(){...})  可以简写成:  $(function(){...})

事件处理
  • on(eve,[sel],[data],fn)
  • off(eve,[sel],[fn])
  • one(type,[data],fn)
  • trigger(type,[data])
  • triggerHandler(type, [data])
    $("").on(eve,[selector],[data],fn)  // 在选择元素上绑定一个或多个事件的事件处理函数.
   // eve: event事件     fn: function事件被触发时执行的函数
    //  .on的[selector]参数是筛选出调用.on方法的dom元素的指定子元素(触发事件的选择器元素的后代), 如:
    //  $('ul').on('click','li', function(){console.log('click');})就是筛选出ul下的li给其绑定click事件;
    [selector]参数的好处:
        在于.on方法为动态添加的元素也能绑上指定事件;如:
        //用$('ul').on('click', 'li', function(){console.log('click');}方式绑定,然后动态添加
        //li:$('ul').append('<li>js new li<li>');这个新生成的li被绑上了click事件.
    [data]参数的调用(必须是键值对形式):
             function myHandler(event) {
                alert(event.data.foo);
             }
             $("li").on("click", {foo: "bar"}, myHandler)
事件切换
  • hover([over,]out)
  • toggle([spe],[eas],[fn])
事件
  • blur([[data],fn])
  • change([[data],fn])
  • click([[data],fn])
  • dblclick([[data],fn])
  • focus([[data],fn])
  • focusin([data],fn)
  • focusout([data],fn)
  • keydown([[data],fn])
  • keypress([[data],fn])
  • keyup([[data],fn])
  • mousedown([[data],fn])
  • mouseenter([[data],fn])
  • mouseleave([[data],fn])
  • mousemove([[data],fn])
  • mouseout([[data],fn])
  • mouseover([[data],fn])
  • mouseup([[data],fn])
  • resize([[data],fn])
  • scroll([[data],fn])
  • select([[data],fn])
  • submit([[data],fn])

实例: 面板拖动

<!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-3.3.1.js"></script>
<script>
    $(function(){
        // 页面加载完成之后自动执行
        $('#title').mouseover(function(){
            $(this).css('cursor','move');
        }).mousedown(function(e){
            var _event = e || window.event;
            // 原始鼠标横纵坐标位置
            var ord_x = _event.clientX;
            var ord_y = _event.clientY;

            var parent_left = $(this).parent().offset().left;
            var parent_top = $(this).parent().offset().top;

            $(this).bind('mousemove', function(e){   // 用$(this).on("mousemove",function (e){也行
                var _new_event = e || window.event;
                var new_x = _new_event.clientX;
                var new_y = _new_event.clientY;

                var x = parent_left + (new_x - ord_x);
                var y = parent_top + (new_y - ord_y);

                $(this).parent().css('left',x+'px');
                $(this).parent().css('top',y+'px');

            })
        }).mouseup(function(){
            $(this).unbind('mousemove');  // 用$(this).off("mousemove")也行
        });
    })
</script>
</body>
</html>
View Code

实例: 放大镜

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>bigger</title>
    <style>
        *{
            margin: 0;
            padding:0;
        }
        .outer{
            height: 350px;
            width: 350px;
            border: dashed 5px cornflowerblue;
        }
        .outer .small_box{
            position: relative;
        }
        .outer .small_box .float{
            height: 175px;
            width: 175px;
            background-color: darkgray;
            opacity: 0.4;
            fill-opacity: 0.4;
            position: absolute;
            display: none;

        }

        .outer .big_box{
            height: 400px;
            width: 400px;
            overflow: hidden;
            position:absolute;
            left: 360px;
            top: 0px;
            z-index: 1;
            border: 5px solid rebeccapurple;
            display: none;
        }
        .outer .big_box img{
            position: absolute;
            z-index: 5;
        }
    </style>
</head>
<body>
        <div class="outer">
            <div class="small_box">
                <div class="float"></div>
                <img src="samll.jpg">
            </div>
            <div class="big_box">
                <img src="big.jpg">
            </div>
        </div>
        
<script src="jquery-3.3.1.js"></script>
<script>
    $(function(){

          $(".small_box").mouseover(function(){
              $(".float").css("display","block");
              $(".big_box").css("display","block")
          });
          $(".small_box").mouseout(function(){
              $(".float").css("display","none");
              $(".big_box").css("display","none")
          });

          $(".small_box").mousemove(function(e){
              var _event=e || window.event;

              var float_width=$(".float").width();
              var float_height=$(".float").height();

              console.log(float_height,float_width);

              var float_height_half=float_height/2;
              var float_width_half=float_width/2;
              console.log(float_height_half,float_width_half);
              
              var small_box_width=$(".small_box").height();
              var small_box_height=$(".small_box").width();



//  鼠标点距离左边界的长度与float应该与左边界的距离差半个float的width,height同理
              var mouse_left=_event.clientX-float_width_half;
              var mouse_top=_event.clientY-float_height_half;

              if(mouse_left<0){
                  mouse_left=0
              }else if (mouse_left>small_box_width-float_width){
                  mouse_left=small_box_width-float_width
              }

              if(mouse_top<0){
                  mouse_top=0
              }else if (mouse_top>small_box_height-float_height){
                  mouse_top=small_box_height-float_height
              }

               $(".float").css("left",mouse_left+"px");
               $(".float").css("top",mouse_top+"px")

               var percentX=($(".big_box img").width()-$(".big_box").width())/ (small_box_width-float_width);
               var percentY=($(".big_box img").height()-$(".big_box").height())/(small_box_height-float_height);

              console.log(percentX,percentY)

               $(".big_box img").css("left", -percentX*mouse_left+"px")
               $(".big_box img").css("top", -percentY*mouse_top+"px")
          })
    })
</script>
</body>
</html>
View Code

 


动画效果

显示隐藏

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<p style="display: none">hello world</p>
<input id="show" type="button" value="显示">
<input id="hide" type="button" value="隐藏">
<input id="toggle" type="button" value="toggle">
<script src="jquery-3.3.1.js"></script>
<script>
    $("#show").click(function () {
             $("p").show(2000,function () {
                 alert(123)
             });
    });

    $("#hide").click(function () {
             $("p").hide(1000);
    });

     $("#toggle").click(function () {
             $("p").toggle(1000);
    });
</script>    
</body>
</html>
View Code

淡入淡出

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="div" style="display:none ;width: 200px;height: 200px;background-color: rebeccapurple"></div>

<input id="In" type="button" value="fadeIn">
<input id="out" type="button" value="fadeout">
<input id="toggle" type="button" value="fadetoggle">
<input id="fadeto" type="button" value="fadeto">

<script src="jquery-3.3.1.js"></script>
<script>
    $("#In").click(function () {
        $("div").fadeIn(2000);
    })

    $("#out").click(function () {
        $("div").fadeOut(1000);
    })

     $("#toggle").click(function () {
        $("div").fadeToggle(1000);
    });

    $("#fadeto").click(function () {
        $("div").fadeTo(1000,0.9);  //0.9为透明度
    });
</script>
</body>
</html>
View Code

滑动

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery-3.3.1.js"></script>
    <script>
    $(document).ready(function(){
     $("#flipshow").click(function(){
         $("#content").slideDown(1000);
     });
      $("#fliphide").click(function(){
         $("#content").slideUp(1000);
     });
      $("#toggle").click(function(){
         $("#content").slideToggle(1000);
     })
  });
    </script>
    <style>
        #flipshow,#content,#fliphide,#toggle{
            padding: 5px;
            text-align: center;
            background-color: blueviolet;
            border:solid 1px red;
        }
        #content{
            padding: 50px;
            display: none;
        }
    </style>
</head>
<body>
    <div id="flipshow">出现</div>
    <div id="fliphide">隐藏</div>
    <div id="toggle">toggle</div>

    <div id="content">helloworld</div>
</body>
</html>
View Code

回调函数

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery-3.3.1.js"></script>
    <script>
        $(document).ready(function(){
            $("button").click(function(){
                $("p").hide(1000,function(){
                    alert('动画结束')
                })
                // $("p").css('color','red').slideUp(1000).slideDown(2000)
            })
        });
    </script>
</head>
<body>
    <button>隐藏</button>
    <p>helloworld helloworld helloworld</p>
</body>
</html>
View Code

 


扩展方法 (插件机制)

一. 用JQuery写插件时, 有两个方法:

$.extend(object): 为JQuery 添加一个静态方法, 即可以直接调用

$.fn.extend(object): 为JQuery实例添加一个方法, 即前面要有个标签才能调用

<script>
    jQuery.extend({
          min: function(a, b) { return a < b ? a : b; },
          max: function(a, b) { return a > b ? a : b; }
        });
    console.log($.min(3,4));   //直接调用

//-----------------------------------------------------------------------

  $.fn.extend({
      "print":function(){
          for (var i=0;i<this.length;i++){
              console.log($(this)[i].innerHTML)
          }
      }
  });
  $("p").print();    //前面有标签才能调用
</script>

二. 定义作用域

      定义一个JQuery插件, 首先要为这个插件定义私有作用域. 外部的代码不能直接访问插件内部的代码, 插件内部的代码不污染全局变量. 在一定的作用上减低了插件与运行环境的依赖.

//将extend放在一个自执行函数里, 为了加一个私有域, 保护内部变量不受外部干扰
    (function ($) {
        var num=13;
        $.fn.extend({
            print:function () {
                console.log($(this).html())
            }
        });
    })(jQuery);

    $("p").print()

 三. 默认参数

定义了jQuery插件之后, 如果希望某些参数具有默认值, 可以以这种方式来指定.

//步骤1 定义JQuery的作用域
(function ($) {
    //步骤3-a 插件的默认值属性
    var defaults = {
        prevId: 'prevBtn',
        prevText: 'Previous',
        nextId: 'nextBtn',
        nextText: 'Next'
        //……
    };
    //步骤6-a 在插件里定义方法
    var showLink = function (obj) {
        $(obj).append(function () { return "(" + $(obj).attr("href") + ")" });
    }

    //步骤2 插件的扩展方法名称
    $.fn.easySlider = function (options) {
        //步骤3-b 合并用户自定义属性,默认属性
        var options = $.extend(defaults, options);
        //步骤4 支持JQuery选择器
        //步骤5 支持链式调用
        return this.each(function () {
            //步骤6-b 在插件里定义方法
            showLink(this);
        });
    }
})(jQuery);  
View Code

 


实例练习

注册验证

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<form class="Form">
    <p>用户名: <input class="v1" type="text" name="username" mark="用户名"></p>
    <p>邮箱: <input class="v1" type="text" name="email" mark="邮箱"></p>
    <p><input class="v1" type="submit" value="submit"  onclick="return validate()"></p>
</form>

<script src="jquery-3.3.1.js"></script>
<script>
    // 注意:
    // DOM对象--->jquery对象    $(DOM)
    // jquery对象--->DOM对象    $("")[0]
    //---------------------------------------------------------
    // DOM绑定版本
    function validate(){
        flag=true;

        $("Form .v1").each(function(){
            $(this).next("span").remove();// 防止对此点击按钮产生多个span标签
            var value=$(this).val();
            if (value.trim().length==0){
                 var mark=$(this).attr("mark");
                 console.log(mark)
                 var ele=document.createElement("span");
                 ele.innerHTML=mark+"不能为空!";
                 $(this).after(ele);
                 $(ele).prop("class","error");// DOM对象转换为jquery对象
                 flag=false;   //有问题, 最后return false, 数据不会被提交
            }
        });

        return flag
    }
    $(".Form :submit").click(function(){});
</script>
</body>
</html>
View Code

滚动菜单

<!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>
    <div onclick="GoTop();" style="cursor: pointer; position: fixed;right: 0;bottom: 0;width: 50px;height: 50px;background-color: #303a40;color: white;border: 1px solid red;">返回顶部</div>

    <script type="text/javascript" src="jquery-3.3.1.js"></script>
    <script type="text/javascript">
        function  GoTop() {
            $(window).scrollTop(0);
        }
        $(function(){
            Init();
        });
        function Init(){   //     或者直接写 window.onscroll=function(){ 也可以
            $(window).scroll(function() {
                var scrollTop = $(window).scrollTop();
                if(scrollTop > 50){
                    $('.catalog').addClass('fixed');
                }else{
                    $('.catalog').removeClass('fixed');
                }
                $('.content').children().each(function(){
                    var offSet = $(this).offset();
                    var offTop = offSet.top - scrollTop;
                    var height = $(this).height();

                    if(offTop<=0 && offTop> -height){
                        //去除其他
                        //添加自己
                        var docHeight = $(document).height();
                        var winHeight = $(window).height();

                        if(docHeight == winHeight+scrollTop)
                        {
                            $('.catalog').children('div:last-child').addClass('active').siblings().removeClass('active');
                        }else{
                            var index = $(this).attr('menu');
                            target='div[auto-to="'+index+'"]';
                            $('.catalog').children(target).addClass('active').siblings().removeClass('active');
                        }
                    }
                });
            });
        }
    </script>
</body>
</html>
View Code

商场菜单

<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width">
    <meta http-equiv="X-UA-Compatible" content="IE=8">
    <title>购物商城</title>
    <style>

*{
    margin: 0;
    padding: 0;
}
.hide{
    display:none;
}


.header-nav {
    height: 39px;
    background: #c9033b;
}
.header-nav .bg{
    background: #c9033b;
}

.header-nav .nav-allgoods .menuEvent {
    display: block;
    height: 39px;
    line-height: 39px;
    text-decoration: none;
    color: #fff;
    text-align: center;
    font-weight: bold;
    font-family: 微软雅黑;
    color: #fff;
    width: 100px;
}
.header-nav .nav-allgoods .menuEvent .catName {
    height: 39px;
    line-height: 39px;
    font-size: 15px;
}

.header-nav .nav-allmenu a {
    display: inline-block;
    height: 39px;
    vertical-align: top;
    padding: 0 15px;
    text-decoration: none;
    color: #fff;
    float: left;
}

.header-menu a{
    color:#656565;
}

.header-menu .menu-catagory{
    position: absolute;
    background-color: #fff;
    border-left:1px solid #fff;
    height: 316px;
    width: 230px;
     z-index: 4;
     float: left;
}
.header-menu .menu-catagory .catagory {
    border-left:4px solid #fff;
    height: 104px;
    border-bottom: solid 1px #eaeaea;
}
.header-menu .menu-catagory .catagory:hover {
    height: 102px;
    border-left:4px solid #c9033b;
    border-bottom: solid 1px #bcbcbc;
    border-top: solid 1px #bcbcbc;
}

.header-menu .menu-content .item{
    margin-left:230px;
    position:absolute;
    background-color:white;
    height:314px;
    width:500px;
    z-index:4;
    float:left;
    border: solid 1px #bcbcbc;
    border-left:0;
    box-shadow: 1px 1px 5px #999;
}

    </style>
</head>
<body>

<div class="pg-header">

    <div class="header-nav">
        <div class="container narrow bg">
            <div class="nav-allgoods left">
                <a id="all_menu_catagory" href="#" class="menuEvent">
                    <strong class="catName">全部商品分类</strong>
                    <span class="arrow" style="display: inline-block;vertical-align: top;"></span>
                </a>
            </div>
        </div>
    </div>
    <div class="header-menu">
        <div class="container narrow hide">
            <div id="nav_all_menu" class="menu-catagory">
                <div class="catagory" float-content="one">
                    <div class="title">家电</div>
                    <div class="body">
                        <a href="#">空调</a>
                    </div>
                </div>
                <div class="catagory" float-content="two">
                    <div class="title">床上用品</div>
                    <div class="body">
                        <a href="http://www.baidu.com">床单</a>
                    </div>
                </div>
                <div class="catagory" float-content="three">
                    <div class="title">水果</div>
                    <div class="body">
                        <a href="#">橘子</a>
                    </div>
                </div>
            </div>

            <div id="nav_all_content" class="menu-content">
                <div class="item hide" float-id="one">

                    <dl>
                        <dt><a href="#" class="red">厨房用品</a></dt>
                        <dd>
                            <span>| <a href="#" target="_blank" title="勺子">勺子</a></span>
                        </dd>
                    </dl>
                    <dl>
                        <dt><a href="#" class="red">厨房用品</a></dt>
                        <dd>
                            <span>| <a href="#" target="_blank" title="菜刀">菜刀</a></span>

                        </dd>
                    </dl>
                    <dl>
                        <dt><a href="#" class="red">厨房用品</a></dt>
                        <dd>
                            <span>| <a href="#">菜板</a></span>
                        </dd>
                    </dl>
                    <dl>
                        <dt><a href="#" class="red">厨房用品</a></dt>
                        <dd>
                            <span>| <a href="#" target="_blank" title="碗"></a></span>

                        </dd>
                    </dl>

                </div>
                <div class="item hide" float-id="two">
                    <dl>
                        <dt><a href="#" class="red">厨房用品</a></dt>
                        <dd>
                            <span>| <a href="#" target="_blank" title="">角阀</a></span>

                        </dd>
                    </dl>
                    <dl>
                        <dt><a href="#" class="red">厨房用品</a></dt>
                        <dd>
                            <span>| <a href="#" target="_blank" title="角阀">角阀</a></span>

                        </dd>
                    </dl>
                    <dl>
                        <dt><a href="#" class="red">厨房用品</a></dt>
                        <dd>
                            <span>| <a href="#" target="_blank" title="角阀">角阀</a></span>

                        </dd>
                    </dl>

                </div>
                <div class="item hide" float-id="three">
                    <dl>
                        <dt><a href="#" class="red">厨房用品3</a></dt>
                        <dd>
                            <span>| <a href="#" target="_blank" title="角阀">角阀3</a></span>

                        </dd>
                    </dl>
                    <dl>
                        <dt><a href="#" class="red">厨房用品3</a></dt>
                        <dd>
                            <span>| <a href="http://www.meilele.com/category-jiaofa/" target="_blank" title="角阀">角阀3</a></span>

                        </dd>
                    </dl>
                </div>
            </div>
        </div>
    </div>

</div>


<script src="jquery-3.3.1.js"></script>

<script type="text/javascript">
    $(document).ready(function () {

        Change_Menu('#all_menu_catagory','#nav_all_menu', '#nav_all_content');

    });



    function Change_Menu(all_menu_catagory,menu, content) {
        $all_menu_catagory = $(all_menu_catagory);
        $menu = $(menu);
        $content = $(content);

        $all_menu_catagory.bind("mouseover", function () {
            $menu.parent().removeClass('hide');
        });
        $all_menu_catagory.bind("mouseout", function () {
            $menu.parent().addClass('hide');
        });

        $menu.children().bind("mouseover", function () {
            $menu.parent().removeClass('hide');
            $item_content = $content.find('div[float-id="' + $(this).attr("float-content") + '"]');
            $item_content.removeClass('hide').siblings().addClass('hide');
        });
        $menu.bind("mouseout", function () {
            $content.children().addClass('hide');
            $menu.parent().addClass('hide');
        });
        $content.children().bind("mouseover", function () {

            $menu.parent().removeClass('hide');
            $(this).removeClass('hide');
        });
        $content.children().bind("mouseout", function () {

            $(this).addClass('hide');
            $menu.parent().addClass('hide');
        });
    }
</script>
</body>
</html>
View Code

编辑框

<!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>
        </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" sel-val="1" global-key="STATUS">在线</td>
            </tr>
            <tr>
                <td><input type="checkbox" /></td>
                <td edit="true">v1</td>
                <td>v11</td>
                <td edit="true" edit-type="select" sel-val="2" global-key="STATUS">下线</td>
            </tr>
            <tr>
                <td><input type="checkbox" /></td>
                <td edit="true">v1</td>
                <td>v11</td>
                <td edit="true" edit-type="select" sel-val="1" global-key="STATUS">在线</td>
            </tr>
        </tbody>
    </table>

    <script type="text/javascript" src="jquery-3.3.1.js"></script>
    <script>
        /*
         监听是否已经按下control键
         */
        window.globalCtrlKeyPress = false;

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

        /*
         按下Control,联动表格中正在编辑的select
         */
        function MultiSelect(ths){
            if(window.globalCtrlKeyPress){
                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);
                });
            }
        }
    </script>
    <script type="text/javascript">

$(function(){
    BindSingleCheck('#edit_mode', '#tb1');
});

function BindSingleCheck(mode, tb){

    $(tb).find(':checkbox').bind('click', function(){
        var $tr = $(this).parent().parent();
        if($(mode).hasClass('editing')){
            if($(this).prop('checked')){
                RowIntoEdit($tr);
            }else{
                RowOutEdit($tr);
            }
        }
    });
}

function CreateSelect(attrs,csses,option_dict,item_key,item_value,current_val){
    var sel= document.createElement('select');
    $.each(attrs,function(k,v){
        $(sel).attr(k,v);
    });
    $.each(csses,function(k,v){
        $(sel).css(k,v);
    });
    $.each(option_dict,function(k,v){
        var opt1=document.createElement('option');
        var sel_text = v[item_value];
        var sel_value = v[item_key];

        if(sel_value==current_val){
            $(opt1).text(sel_text).attr('value', sel_value).attr('text', sel_text).attr('selected',true).appendTo($(sel));
        }else{
            $(opt1).text(sel_text).attr('value', sel_value).attr('text', sel_text).appendTo($(sel));
        }
    });
    return sel;
}

STATUS = [
    {'id': 1, 'value': "在线"},
    {'id': 2, 'value': "下线"}
];

BUSINESS = [
    {'id': 1, 'value': "车上会"},
    {'id': 2, 'value': "二手车"}
];

function RowIntoEdit($tr){
    $tr.children().each(function(){
        if($(this).attr('edit') == "true"){
            if($(this).attr('edit-type') == "select"){
                var select_val = $(this).attr('sel-val');
                var global_key = $(this).attr('global-key');
                var selelct_tag = CreateSelect({"onchange": "MultiSelect(this);"}, {}, window[global_key], 'id', 'value', select_val);
                $(this).html(selelct_tag);
            }else{
                var orgin_value = $(this).text();
                var temp = "<input value='"+ orgin_value+"' />";
                $(this).html(temp);
            }

        }
    });
}

function RowOutEdit($tr){
    $tr.children().each(function(){
        if($(this).attr('edit') == "true"){
            if($(this).attr('edit-type') == "select"){
                var new_val = $(this).children(':first').val();
                var new_text = $(this).children(':first').find("option[value='"+new_val+"']").text();
                $(this).attr('sel-val', new_val);
                $(this).text(new_text);
            }else{
                var orgin_value = $(this).children().first().val();
                $(this).text(orgin_value);
            }

        }
    });
}

function CheckAll(mode, tb){
    if($(mode).hasClass('editing')){

        $(tb).children().each(function(){

            var tr = $(this);
            var check_box = tr.children().first().find(':checkbox');
            if(check_box.prop('checked')){

            }else{
                check_box.prop('checked',true);

                RowIntoEdit(tr);
            }
        });

    }else{

        $(tb).find(':checkbox').prop('checked', true);
    }
}

function CheckReverse(mode, tb){

    if($(mode).hasClass('editing')){

        $(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);
                RowOutEdit(tr);
            }else{
                check_box.prop('checked',true);
                RowIntoEdit(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 CheckCancel(mode, tb){
    if($(mode).hasClass('editing')){
        $(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);
                RowOutEdit(tr);

            }else{

            }
        });

    }else{
        $(tb).find(':checkbox').prop('checked', false);
    }
}

function EditMode(ths, tb){
    if($(ths).hasClass('editing')){
        $(ths).removeClass('editing');
        $(tb).children().each(function(){
            var tr = $(this);
            var check_box = tr.children().first().find(':checkbox');
            if(check_box.prop('checked')){
                RowOutEdit(tr);
            }else{

            }
        });

    }else{

        $(ths).addClass('editing');
        $(tb).children().each(function(){
            var tr = $(this);
            var check_box = tr.children().first().find(':checkbox');
            if(check_box.prop('checked')){
                RowIntoEdit(tr);
            }else{

            }
        });

    }
}
    </script>

</body>
</html>
View Code

  


jQuery API中文文档

w3school jQuery教程

 

posted @ 2018-03-14 13:32  Charonnnnn  阅读(142)  评论(0)    收藏  举报