zoukankan      html  css  js  c++  java
  • jquery知识

    一 jQuery是什么? 

    [1]   jQuery由美国人John Resig创建,至今已吸引了来自世界各地的众多 javascript高手加入其team。

    [2]   jQuery是继prototype之后又一个优秀的Javascript框架。其宗旨是——WRITE LESS,DO MORE!

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

    [4]  jQuery是一个快速的,简洁的javaScript库,使用户能更方便地处理HTMLdocuments、events、实现动画效果,并且方便地为网站提供AJAX交互。

    [5]  jQuery还有一个比较大的优势是,它的文档说明很全,而且各种应用也说得很详细,同时还有许多成熟的插件可供选择。

    二 什么是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对象,加【0】因为是个数组集合 $("#msg").html(); $("#msg")[0].innerHTML

     jquery的基础语法:$(selector).action()      selector 选择器 

     参考:http://jquery.cuishifeng.cn/

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

    3.1   选择器

    3.1.1 基本选择器      

    - ID选择器                   $("#id")
    - 类选择器(class)           $(".class")
    - 标签选择器(html标签)        $("element")
    - 所有标签                   $("*")
    - 组合选择器                 $("#id,.class")

    3.1.2 层级选择器   

    $(".outer div")后代   $(".outer>div")子代  $(".outer+div")匹配所有紧随outer元素之后的同级元素div,紧挨着兄弟  $(".outer~div")普通兄弟,可以不挨着

    3.1.3 基本筛选器  

    - 写在引号里面的:过滤的意思,注意parent
    索引            
    $(" :first")    第一个
    $(" :not('')")  否 非,不要
    $(" :even")     偶数,按照索引
    $(" :odd")      奇数
    $(" :eq")       索引等于
    $(" :gt")       大于索引
    $(" :lt")       小于
    $(" :last")     最后一个
    $(" :focus")    获取焦点
                    
    内容
    $(" :contains('')")     包含
    $(" :empty")            文档空的
    $(" :has('')")          含有
    $(" :parent")  *****   区别于$("").parent()
                    
    可见性
    $(" :hidden)
    $(" :visible")

    3.1.4 属性选择器

    input标签,里面有name属性,type类型
    [name] -------------> 有name属性的input [type='password'] --> 类型是password的input标签
    自定义属性
    <div jj='lala'></div>
    $('[jj]').css('color','red')
    $('[jj='lala']').css('color','red')

    3.1.5 表单选择器      

    针对是表单的type类型

    $("[type='text']") 跟属性选择器一样了   
    ----->$(":text")  冒号前面不需要写东西,因为只适用于表单标签,自动识别为type:?
    :password
    :checkbox
    :radio
    :text
    :submit
    :button
    :image
    :file

    3.1.6 表单属性选择器

    针对表单的默认操作

        注意只适用于input标签  : $("input:checked")
        :enabled
        :disabled
        :checked
        :selected
    <body>
    
    <form>
        <input type="checkbox" value="123" checked>
        <input type="checkbox" value="456" checked>
    
    
      <select>
          <option value="1">Flowers</option>
          <option value="2" selected="selected">Gardens</option>
          <option value="3" selected="selected">Trees</option>
          <option value="3" selected="selected">Trees</option>
      </select>
    </form>
    
    
    <script src="jquery.min.js"></script>
    <script>
        // console.log($("input:checked").length);     // 2
    
        // console.log($("option:selected").length);   // 只能默认选中一个,所以只能lenth:1
    
        $("input:checked").each(function(){
    
            console.log($(this).val())
        })
    
    </script>
    
    
    </body>
    View Code

    3.2 筛选器

    3.2.1  过滤筛选器    

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

    和基本筛选器的区别

    var i=3;
    $(".c1:eq(i)").css("color",'red');     局限性,里面是字符串
    $(".c1").eq(i).css("color",'red');    可以引入变量
    console.log($("#d1").hasClass("c1"))   true,判断是否有这个标签

    3.2.2  查找筛选器  

     查找子标签:         $("div").children(".test")子代里面的test儿子(括号可加可不加,不加就是子代)       
                $("div").find(".test")后代里面的test(括号里面需要加条件) 向下查找兄弟标签: $(".test").next() $(".test").nextAll() 下面所有标签
    $(".test").nextUntil('test?') 直到哪变红,不会到test,开区间 向上查找兄弟标签: $("div").prev() $("div").prevAll()
    $("div").prevUntil('#div?') 直到哪变红,不会到div?,开区间
    查找所有兄弟标签: $("div").siblings()        上下兄弟都算
    查找父标签: $(".test").parent()第一层父 $(".test").parents()所有父
    $(".test").parentUntil() 直到。。。

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

    4.1 事件

    页面载入

    文档加载完毕后,执行里面代码

    1
    2
    3
    ready(fn)  // 当DOM载入就绪可以查询及操纵时绑定一个要执行的函数。
    $(document).ready(function(){}) -----------> $(function(){}) 
    $(function(){....jquery操作});
       $(function () {
    
                $("button").click(function () {
                        var $li=$("<li>"); //  <li></li>
    
                        $li.html("444");
    
                        $("ul").append($li)
                });
    
    
                $("ul").on("click","li",function () {
                    alert(123)
                });
    
           });
    
    
          $(document).ready(function () {  # 加载文档完毕后,执行函数
              pass
          })
    加载文档

    事件绑定

    第一种方法

    //语法:  标签对象.事件(函数)    
    eg: $("p").click(function(){})
       $("button").click(function () {
           alert(123)
       });
    事件绑定第一种

    第二种方法

    $('.c1').bind('click',function(){
    
    })
    
    $('.c1').unbind('click',function(){
        
    })
    bind绑定

    第三种方法

    $('.c').delegate('a', 'click', function(){
    
    })
    $('.c').undelegate('a', 'click', function(){
    
    })
    delegate绑定

    第四种方法

    第一种是第四种的简写,因为新创建的标签无法继承父标签的事件,通常on用于事件委派,delegate也是调用On.

    $("button").on("click",function () {
      alert(123)
    });

    事件委派:

    我交给你,托付给你事件,标签的父标签

    $("").on(eve,[selector],[data],fn)  // 在选择元素上绑定一个或多个事件的事件处理函数。
    <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
    </ul>
    <hr>
    <button id="add_li">Add_li</button>
    <button id="off">off</button>
    
    <script src="jquery.min.js"></script>
    <script>
    $("#add_li").click(function(){ # 创建标签 var $ele=$("<li>"); $ele.text(Math.round(Math.random()*10)); $("ul").append($ele) }); $("ul").on("click","li",function(){ # 这里是委派,找到ul给li委派点击事件 alert(456) # 新创建的标签也会有点击事件 }) </script>

    事件切换

    hover事件:

    一个模仿悬停事件(鼠标移动到一个对象上面及移出这个对象)的方法。这是一个自定义的方法,它为频繁使用的任务提供了一种“保持在其中”的状态。

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

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

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <style>
            *{
                margin: 0;
                padding: 0;
            }
            .test{
    
                 200px;
                height: 200px;
                background-color: wheat;
    
            }
        </style>
    </head>
    <body>
    
    
    <div class="test"></div>
    </body>
    <script src="jquery.min.js"></script>
    <script>
    //    function enter(){
    //        console.log("enter")
    //    }
    //    function out(){
    //        console.log("out")
    //    }
    // $(".test").hover(enter,out)
    
    
    $(".test").mouseenter(function(){
            console.log("enter")
    });
    
    $(".test").mouseleave(function(){
            console.log("leave")
        });
    
    </script>
    </html>
    View Code

    示例里面定义了2种写发,建议第二种

    4.2 操作

    ----------------------------------------------------------样式操作
    1. $("").addClass(class|fn)           # 给class类里面添加个新类
    addClass("has-error")                 # cl='has-error form'
    2. $("").removeClass([class|fn])
    3. toggleClass(class|fn[,sw])  切换,有就去掉,没有就加上
    
    ----------------------------------------------------------属性操作  
    1. $("").attr();
    attr(name|pro|key,val|fn)
      - 一个参数 获取属性的值
      - 两个参数 设置属性的值
      - 点击加载图片
      $('img').attr('src','img1')
    
    2. $("").removeAttr();
    removeAttr(name)
     - 删除属性的值
    
    3. $("").prop();  
    prop(n|p|k,v|f)  属性的返回值是布尔类型,一般是checked,selected,用于html本身固定属性,attr用于自定义属性 详情见示例
     $(':radio').prop('checked',false)
    
    4. $("").removeProp();
    removeProp(name)
      - 删除属性的值
    
    ------------------------------------------------ 文本操作。HTML代码/文本/值
    1. $("").html([val|fn])     html元素文本
    加 html标签
    .html("<span>老师,我好饿。</span>")
    
    2. $("").text([val|fn])     文本
    加文本 
    .text("老师,我好饿。")
    
    ------------------------------------------------文本操作。val,针对取的value值,input
    1. $(
    "").val([val|fn|arr]) 属性值,用来固有属性 - input   - 获取的是输入的内容 - checkbox   - 获取的是value值 - select   - 单选 就是获取值 - 多选 得到的是一个数组,设置的时候也要是数组 ----------------------------------------------- css处理 $("#c1").css({"color":"red","fontSize":"35px"})

    attr方法使用:

    <input id="chk1" type="checkbox" />是否可见
    <input id="chk2" type="checkbox" checked="checked" />是否可见
    
    <script>
    
    对于HTML元素本身就带有的固有属性,在处理时,使用prop方法。
    对于HTML元素我们自己自定义的DOM属性,在处理时,使用attr方法。
    像checkbox,radio和select这样的元素,选中属性对应“checked”和“selected”,这些也属于固有属性,因此
    需要使用prop方法去操作才能获得正确的结果。
    
        console.log($("#chk1").prop("checked"));//false
        console.log($("#chk1").attr("checked"));//undefined
    
        console.log($("#chk2").prop("checked"));//true
        console.log($("#chk2").attr("checked"));//checked
    </script>
    attr属性

    文本方法使用

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <script src="jquery-3.1.1.js"></script>
    </head>
    <body>
    
    <p class="p1">P1</p>
    <p class="p1">P2</p>
    <p class="p1">P3</p>
    <p class="p1">p4</p>
    
    <script>
        // DOM对象转为Jquery对象  $(DOM对象)
        $("p").click(function () {
            console.log($(this));
    
            // 取值操作
            //alert($(this).html());
            //alert($(this).text())
    
            // 赋值操作
            $(this).html("<a href=''>hello</a>")
            //$(this).text("<a>hello</a>")
        })
    
    </script>
    
    </body>
    </html>
    文本取赋

    val方法使用

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    
    </head>
    <body>
    
    
    
    <textarea class="c2" ></textarea>
    
    <select name="pro" id="d1">
        <option value="hebei">河北省</option>
        <option value="hubei">湖北省</option>
        <option value="hunan">湖南省</option>
    </select>
    
    <div value="123" class="c3">DIV</div>
    <button>show</button>
    <script src="jquery-3.1.1.js"></script>
    <script>
    
    
        // 取值:
        console.log($(".c1").val()); // 123
        console.log($(".c2").val()); // 123
    
        // 赋值:
         $(".c1").val("hello"); //
         $(".c2").val("hello world") ;//
        
        
        $("button").click(function () {
    //        console.log($(".c2").val())
    //         console.log($("#d1").val())
    
        })
    
    
    
    </script>
    
    </body>
    </html>
    val属性

    灯泡示例:

    .c11 {
                height: 100px;
                 100px;
                border-radius: 50%;
                border: 1px solid #cccccc;
                display: inline-block;
            }
    <div class="c11"></div>
    <button id="switch" class="btn btn-default">开关</button>
    
    $("#switch").on("click", function () {
            // 找灯泡
            $(".c11").toggleClass("c12");
        })
    toggleClass

    左侧菜单:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title></title>
    
        <style>
            *{
                margin: 0;
            }
            .leftbox{
                 20%;
                height: 800px;
                background-color: lightgray;
                float: left;
    
            }
    
            .rightbox{
                 80%;
                height: 800px;
                background-color: aquamarine;
                float: left;
            }
    
            .title{
                text-align: center;
                background-color: coral;
                line-height: 30px;
                margin-top: 10px;
            }
    
            .hide{
                display: none;
            }
        </style>
    
        <script src="jquery-3.1.1.js"></script>
    </head>
    <body>
    
    
    <div class="leftbox">
        <div class="item">
            <div class="title">菜单1</div>
            <div class="con">
                <div>111</div>
                <div>111</div>
                <div>111</div>
            </div>
        </div>
        <div class="item">
            <div class="title">菜单2</div>
            <div class="con hide">
                <div>222</div>
                <div>222</div>
                <div>222</div>
            </div>
            p
        </div>
        <div class="item">
            <div class="title">菜单3</div>
            <div class="con hide">
                <div>333</div>
                <div>333</div>
                <div>333</div>
            </div>
        </div>
    </div>
    <div class="rightbox"></div>
    
    
    <script>
       $(".title").click(function () {
    
    
    //         $(this).next().removeClass("hide");
    //
    //         $(this).parent().siblings().children(".con").addClass("hide")
    
             // jquery支持链式操作
             $(this).next().removeClass("hide").parent().siblings().children(".con").addClass("hide")
    
    
    
       })
    
    </script>
    </body>
    </html>
    左侧菜单

    模态对话框:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <style>
            .hide{
                display: none;
            }
            /*模态*/
            .modal{
                position: fixed;
                top: 50%;
                left: 50%;
                 500px;
                height: 400px;
                margin-left: -250px;
                margin-top: -250px;
                background-color: #eeeeee;
                z-index: 10;
            }
            /*遮罩*/
            .shadow{
                position: fixed;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                opacity: 0.6;
                background-color: black;
                z-index: 9;
            }
        </style>
    </head>
    <body>
        <a onclick="addElement();">添加</a>
    
        // 列表
        <table border="1" id="tb">
            <tr>
                <td target="hostname">1.1.1.11</td>
                <td target="port">80</td>
                <td target="ip">80</td>
                <td>
                    <a class="edit">编辑</a> | <a class="del">删除</a>
                </td>
            </tr>
            <tr>
                <td target="hostname">1.1.1.12</td>
                <td target="port">80</td>
                <td target="ip">80</td>
                <td>
                    <a class="edit">编辑</a> | <a class="del">删除</a>
                </td>
            </tr>
            <tr>
                <td target="hostname">1.1.1.13</td>
                <td target="port">80</td>
                <td target="ip">80</td>
                <td>
                    <a class="edit">编辑</a> | <a class="del">删除</a>
                </td>
            </tr>
            <tr>
                <td target="hostname">1.1.1.14</td>
                <td target="port">80</td>
                <td target="ip">80</td>
                <td>
                    <a class="edit">编辑</a> | <a class="del">删除</a>
                </td>
    
            </tr>
        </table>
        // 模态
        <div class="modal hide">
            <div>
                <input name="hostname" type="text"  />
                <input name="port" type="text" />
                <input name="ip" type="text" />
            </div>
    
            <div>
                <input type="button" value="取消" onclick="cancelModal();" />
                <input type="button" value="确定" onclick="confirmModal();" />
            </div>
        </div>
        // 遮罩
        <div class="shadow hide"></div>
    
        <script src="jquery-1.12.4.js"></script>
        <script>
            // 删除
            $('.del').click(function () {
                $(this).parent().parent().remove();
            });
    
            // 添加确定
            function  confirmModal() {
                var tr = document.createElement('tr');
                var td1 = document.createElement('td');
                td1.innerHTML = "11.11.11.11";
                var td2 = document.createElement('td');
                td2.innerHTML = "8001";
    
                $(tr).append(td1);
                $(tr).append(td2);
    
                $('#tb').append(tr);
    
                $(".modal,.shadow").addClass('hide');
    //            $('.modal input[type="text"]').each(function () {
    //                // var temp = "<td>..."
    //
    //
    //
    //            })
            }
    
            // 模态开始
            function  addElement() {
                $(".modal,.shadow").removeClass('hide');
            }
            // 模态结束
            function cancelModal() {
                $(".modal,.shadow").addClass('hide');
                // 清空脏数据
                $('.modal input[type="text"]').val("");
            }
            // 编辑框
            $('.edit').click(function(){
                $(".modal,.shadow").removeClass('hide');
                // this
                var tds = $(this).parent().prevAll();
                tds.each(function () {
                    // 获取td的target属性值
                    var n = $(this).attr('target');
                    // 获取td中的内容
                    var text = $(this).text();
                    var a1 = '.modal input[name="';
                    var a2 = '"]';
                    var temp = a1 + n + a2;
                    $(temp).val(text);
                });
    
    //            var port = $(tds[0]).text();
    //            var host = $(tds[1]).text();
    //
    //            $('.modal input[name="hostname"]').val(host);
    //            $('.modal input[name="port"]').val(port);
                // 循环获取tds中内容
                // 获取 <td>内容</td> 获取中间的内容
                // 赋值给input标签中的value
    
            });
        </script>
    </body>
    </html>
    modal

    tab菜单:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <style>
            .hide{
                display: none;
            }
            .menu{
                height: 38px;
                background-color: #eeeeee;
                line-height: 38px;
            }
            .active{
                background-color: brown;
            }
            .menu .menu-item{
                float: left;
                border-right: 1px solid red;
                padding: 0 5px;
                cursor: pointer;
            }
            .content{
                min-height: 100px;
                border: 1px solid #eeeeee;
            }
        </style>
    </head>
    <body>
    
        <div style=" 700px;margin:0 auto">
    
            <div class="menu">
                <div  class="menu-item active" a="1">菜单一</div>
                <div  class="menu-item" a="2">菜单二</div>
                <div  class="menu-item" a="3">菜单三</div>
            </div>
            <div class="content">
                <div b="1">内容一</div>
                <div class="hide"  b="2">内容二</div>
                <div class="hide" b="3">内容三</div>
    
            </div>
    
        </div>
        <script src="jquery-1.12.4.js"></script>
        <script>
            $('.menu-item').click(function(){
                $(this).addClass('active').siblings().removeClass('active');
                // var target = $(this).attr('a');
                var target = $(this).index();
                // $('.content').children("[b='"+ target+"']").removeClass('hide').siblings().addClass('hide');
                $('.content').children().eq(target).removeClass('hide').siblings().addClass('hide');
                // $('.content').children().eq($(this).index()).removeClass('hide').siblings().addClass('hide'); 索引
            });
        </script>
    </body>
    </html>
    tab菜单

    $('this').后面加一切的属性后面返回的还是这个this,所以还能继续.加属性操作,因次针对this的多种样式和操作可以归为一行

    4.3 each循环

    我们知道,

    1
    $("p").css("color","red")  

    是将css操作加到所有的标签上,内部维持一个循环;但如果对于选中标签进行不同处理,这时就需要对所有标签数组进行循环遍历啦

    jquery支持两种循环方式:

    方式一

    格式:$.each(obj,fn)

    li=[10,20,30,40];
    dic={name:"yuan",sex:"male"};  也可以循环,并非叫字典,每个语言有自己叫法,只是有这种数据写法
    $.each(li,function(i,x){
        console.log(i,x)
    });
    0,10 i 索引,x值
    1,20
    2,30
    3,40

    方式二

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

    $("tr").each(function(){
        console.log($(this).html())  # 获取当前文本
    })

    其中,$(this)代指当前循环标签。

    $("p").each(function (i) {
        console.log(i);
    
        if(i==1){
            $(this).css("color","red")
        }
        console.log($(this).html())
    })
    循环标签

    each扩展

    如果你想return后下面循环函数继续执行,那么就直接写return或return true
    如果你不想return后下面循环函数继续执行,那么就直接写return false

    /*
            function f(){
    
            for(var i=0;i<4;i++){
    
                if (i==2){
                    return
                }
                console.log(i)
            }
    
        }
        f();  // 这个例子大家应该不会有问题吧!!!
    //-----------------------------------------------------------------------
    
    
        li=[11,22,33,44];
        $.each(li,function(i,v){
    
            if (v==33){
                    return ;   //  ===试一试 return false会怎样?
                }
                console.log(v)
        });
    33,没有打印,
    //------------------------------------------
    
    
        // 大家再考虑: function里的return只是结束了当前的函数,并不会影响后面函数的执行
    
        //本来这样没问题,但因为我们的需求里有很多这样的情况:我们不管循环到第几个函数时,一旦return了,
        //希望后面的函数也不再执行了!基于此,jquery在$.each里又加了一步:
             for(var i in obj){
    
                 ret=func(i,obj[i]) ;
                 if(ret==false){
                     return ;
                 }
    
             }
        // 这样就很灵活了:
        // <1>如果你想return后下面循环函数继续执行,那么就直接写return或return true
        // <2>如果你不想return后下面循环函数继续执行,那么就直接写return false
    
    
    // ---------------------------------------------------------------------
    View Code

    阻止默认事件

    比如一个a标签,你自定义了一个事件,默认还有个a事件,会先走自定义的,再走默认的。那么如果你想走完自己的,阻止默认的

    DoM阻止默认事件
    jquery阻止默认事件

    表单验证

    我们来看下提交表单,并且判断输入,是全部都要验证,还是遇到错误就停止呢?

    框架加载事件绑定与阻止

    事件应用

    input checked  prop 方法且能返回布尔值,attr方法无法动态获取勾中,取消的状态返回undifined

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    
        <input type="button" value="全选" onclick="checkAll();" />
        <input type="button" value="反选" onclick="reverseAll();" />
        <input type="button" value="取消"  onclick="cancleAll();"/>
    
        <table border="1">
            <thead>
                <tr>
                    <th>选项</th>
                    <th>IP</th>
                    <th>PORT</th>
                </tr>
            </thead>
            <tbody id="tb">
    
                <tr>
                    <td><input type="checkbox" /></td>
                    <td>1.1.1.1</td>
                    <td>80</td>
                </tr>
                <tr>
                    <td><input type="checkbox" /></td>
                    <td>1.1.1.1</td>
                    <td>80</td>
                </tr>
                <tr>
                    <td><input type="checkbox" /></td>
                    <td>1.1.1.1</td>
                    <td>80</td>
                </tr>
            </tbody>
        </table>
    
        <script src="jquery-1.12.4.js"></script>
        <script>
            function checkAll() {
                $('#tb :checkbox').prop('checked',true);
            }
            function cancleAll() {
                $('#tb :checkbox').prop('checked',false);
            }
            function reverseAll() {
                $(':checkbox').each(function(k){
                    // this,代指当前循环的每一个元素
                    // Dom
                    /*
                    if(this.checked){
                        this.checked = false;
                    }else{
                        this.checked = true;
                    }
                    */
                    /*
                    if($(this).prop('checked')){
                        $(this).prop('checked', false);
                    }else{
                        $(this).prop('checked', true);
                    }
                    */
                  // 三元运算var v = 条件? 真值:假值
                    var v = $(this).prop('checked')?false:true;
                    $(this).prop('checked',v);
                })
            }
        </script>
    </body>
    </html>
    全选反选

    4.4 文档节点处理

    //创建一个标签对象
        $("<p>")
    
    
    //内部插入
    
        $("").append(content|fn)      ----->$("p").append("<b>Hello</b>");            往后加 与 li同级
        $("").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>");             往后加 与 ul同级
        $("").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>"); 替换  
       replaceAll() //删除 $("").empty() 清空,内部情况 $("").remove([expr]) 删除,整体删除 //复制 $("").clone([Even[,deepEven]]) 复制
       $("button").click(function () {
           var $li=$("<li>"); //  <li></li>
    
           $li.html("444");
    
           $("ul").append($li)
       })
    创建标签
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    
    </head>
    <body>
    
    
    <div class="outer">
    
        <div class="item">
            <button class="add">+</button>
            <input type="text">
        </div>
    
    </div>
    
    <script src="jquery-3.1.1.js"></script>
    <script>
    
         $(".add").click(function () {
    
             var $item=$(this).parent().clone();
             $item.children().first().html("-").attr("class","del_ele");
    
             $(".outer").append($item)
    
         });
    
       $(".outer").on("click",".item .del_ele",function () {
           console.log($(this));
    
           $(this).parent().remove()
       })
    </script>
    </body>
    </html>
    克隆

    4.5 动画效果

    显示隐藏

    show([s,[e],[fn]])     显示
    hide([s,[e],[fn]])     隐藏
    toggle([s],[e],[fn])   切换
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    
    </head>
    <body>
    
    <p>yuan</p>
    
    <button class="xianshi">显示</button>
    <button class="yincang">隐藏</button>
    <button class="qiehuan">切换</button>
    
    <script src="jquery-3.1.1.js"></script>
    <script>
    
        $(".xianshi").click(function () {
            $("p").show(1000)   //1秒内显示
    
        });
    
        $(".yincang").click(function () {
            $("p").hide(1000)  //1秒内隐藏
        });
    
        $(".qiehuan").click(function () {
            $("p").toggle(1000)  //切换
        })
    
    
    </script>
    
    </body>
    </html>
    显示隐藏

    滑动

    slideDown([s],[e],[fn])          关
    slideUp([s,[e],[fn]])            开
    slideToggle([s],[e],[fn])        切换
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <!--<script src="jquery-2.1.4.min.js"></script>/ -->
        <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
        <script>
        $(document).ready(function(){
         $("#slideDown").click(function(){
             $("#content").slideDown(1000);
         });
          $("#slideUp").click(function(){
             $("#content").slideUp(1000);
         });
          $("#slideToggle").click(function(){
             $("#content").slideToggle(1000);
         })
      });
        </script>
        <style>
    
            #content{
                text-align: center;
                background-color: lightblue;
                border:solid 1px red;
                display: none;
                padding: 50px;
            }
        </style>
    </head>
    <body>
    
        <div id="slideDown">出现</div>
        <div id="slideUp">隐藏</div>
        <div id="slideToggle">toggle</div>
    
        <div id="content">helloworld</div>
    
    </body>
    </html>
    滑动显示隐藏

    淡入淡出

    fadeIn([s],[e],[fn])      淡出
    fadeOut([s],[e],[fn])     淡入
    fadeTo([[s],o,[e],[fn]])
        - 淡出到0.66透明度
    fadeToggle([s,[e],[fn]])  切换  由深到浅,透明度的变化
        - .fadeToggle(3000, function () {
       alert("123");
    });
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    
    </head>
    <body>
    
    <img src="egon.jpg" alt="" class="egon">
    
    <p>
        <button class="danru">淡入</button>
        <button class="danchu">淡出</button>
        <button class="danqie">切换</button>
    </p>
    
    
    <script src="jquery-3.1.1.js"></script>
    <script>
    
       $(".danru").click(function () {
           $(".egon").fadeIn(1000)
       });
    
    
       $(".danchu").click(function () {
           $(".egon").fadeOut(1000)
       });
    
    
    
       $(".danqie").click(function () {
           $(".egon").fadeToggle(1000)
       });
    
    
    </script>
    
    </body>
    </html>
    图片淡入淡出

    回调函数

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <!--<script src="jquery-2.1.4.min.js"></script>-->
        <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
    
    </head>
    <body>
      <button>hide</button>
      <p>helloworld helloworld helloworld</p>
    
     <script>
       $("button").click(function(){
           $("p").hide(1000,function(){
               alert($(this).html())
           })
    
       })
        </script>
    </body>
    </html>
    函数嵌套

    4.6 css操作

    $('t1').css('样式名称', '样式值')

    点赞:

    点赞+

    css位置操作

    $("").offset([coordinates])          偏移量
    相对定位相对可是窗口
        - 获取相对位置
        - 比较的对象是 html
    $("").position()
    绝对定位相对位移的变化
        - 获取相对已经定位的父标签的位置
        - 比较的是最近的那个做过定位的祖先标签
        加括号可以查看位置    .position().left
    $("").scrollTop([val])
        - $(window).scrollTop()
        - 返回顶部
    $("").scrollLeft([val])

    偏移量

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <style>
            body{
                margin: 0;
            }
            .c1{
                 200px;
                height: 200px;
                background-color: #2459a2;
            }
        </style>
    </head>
    <body>
    
    
    
    <div class="c1"></div>
    <button>change</button>
    <script src="jquery-3.1.1.js"></script>
    
    <script>
    
        // offset方法的参照物是可视窗口
        console.log($(".c1").offset());         // 偏移量对象
        console.log($(".c1").offset().top);     // 偏移量对象
        console.log($(".c1").offset().left);     // 偏移量对象
        
    //    var top1=100
        $("button").click(function () {
            $(".c1").offset({"top":100,left:200})
        })
    </script>
    </body>
    </html>
    offset

    定位

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <style>
            *{
                margin: 0;
            }
            .box1{
                 200px;
                height: 200px;
                background-color: rebeccapurple;
            }
            .box2{
                 200px;
                height: 200px;
                background-color: darkcyan;
            }
            .parent_box{
                 position: relative;
            }
        </style>
    </head>
    <body>
    
    <div class="box1"></div>
    <div class="parent_box">
        <div class="box2"></div>
    </div>
    <p></p>
    
    
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
    <script>
        var $position=$(".box2").position();
        var $left=$position.left;
        var $top=$position.top;
    
    </script>
    </body>
    </html>
    
    针对父亲位置,前提父亲一定是可定位了的
    position

    返回顶部

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    
        <style>
            body{
                margin: 0;
            }
            .returnTop{
                height: 60px;
                 100px;
                background-color: peru;
                position: fixed;
                right: 0;
                bottom: 0;
                color: white;
                line-height: 60px;
                text-align: center;
            }
            .div1{
                background-color: wheat;
                font-size: 5px;
                overflow: auto;
                 500px;
                height: 200px;
            }
            .div2{
                background-color: darkgrey;
                height: 2400px;
            }
    
    
            .hide{
                display: none;
            }
        </style>
    </head>
    <body>
         <div class="div1 div">
               <h1>hello</h1>
               <h1>hello</h1>
               <h1>hello</h1>
               <h1>hello</h1>
               <h1>hello</h1>
               <h1>hello</h1>
               <h1>hello</h1>
               <h1>hello</h1>
               <h1>hello</h1>
               <h1>hello</h1>
               <h1>hello</h1>
               <h1>hello</h1>
               <h1>hello</h1>
               <h1>hello</h1>
               <h1>hello</h1>
               <h1>hello</h1>
         </div>
         <div class="div2 div"></div>
         <div class="returnTop hide">返回顶部</div>
    
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
        <script>
             $(window).scroll(function(){
                 var current=$(window).scrollTop();
                  console.log(current);
                  if (current>100){
    
                      $(".returnTop").removeClass("hide")
                  }
                  else {
                  $(".returnTop").addClass("hide")
              }
             });
    
    
                $(".returnTop").click(function(){
                    $(window).scrollTop(0)
                });
    
    
        </script>
    </body>
    </html>
    scrollTop

    尺寸操作

    $("").height([val|fn])
    - 元素的高度
    $("").width([val|fn])
    - 元素的宽度
    $("").innerHeight()
    - 带padding的高度
    $("").innerWidth()
    $("").outerHeight([soptions])
    在innerHeight的基础上再加border的高度
    $("").outerWidth([options])

    示例:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <style>
            *{
                margin: 0;
            }
            .box1{
                 200px;
                height: 200px;
                background-color: wheat;
                padding: 50px;
                border: 50px solid rebeccapurple;
                margin: 50px;
            }
    
        </style>
    </head>
    <body>
    
    
    
    
    <div class="box1">
        DIVDIDVIDIV
    </div>
    
    
    <p></p>
    
    <script src="jquery-3.1.1.js"></script>
    <script>
        var $height=$(".box1").height();
        var $innerHeight=$(".box1").innerHeight();
        var $outerHeight=$(".box1").outerHeight();
        var $margin=$(".box1").outerHeight(true);
    
        $("p").text($height+"---"+$innerHeight+"-----"+$outerHeight+"-------"+$margin)
    </script>
    </body>
    </html>
    View Code

    扩展方法 (插件机制)

    jQuery.extend(object)

    扩展jQuery对象本身。

    用来在jQuery命名空间上增加新函数。 

    在jQuery命名空间上增加两个函数:

    $.extend({
       'liqianlong': function () {
           return 'sb';
       }
    });
    var v = $.liqianlong(); 
    alert(v);

    jQuery.fn.extend(object)

    扩展 jQuery 元素集来提供新的方法(通常用来制作插件)

    增加两个插件方法:

    $.fn.extend({
       "liqianlong": function () {
           return 'db';
       }
    });
    var v = $('#i1').liqianlong(); 这种需要选择器。
    alert(v);

    如果要引入插件,可以通过引入js实现

    //html
    <script src="plugin1.js"></script>
    
    //js文件
    status = 1;
    
    $.extend({
       'liqianlong': function () {
           return 'sb';
       }
    });

    如果引入插件过多,而且有相同的变量的情况,考虑自执行函数,因为js作用域是函数

    //html
    <script src="plugin1.js"></script>
    
    //文件
    (function (arg) {
        var status = 1;
        arg.extend({
           'liqianlong': function () {
               return 'sb';
           }
        });
    
    })(jQuery); //$都可以传
  • 相关阅读:
    设置C#Web网页Session超时丢失时间
    docker19.03限制容器使用的cpu资源
    centos8平台搭建mysql8数据库主从同步
    centos8平台使用slabtop监控slab内存的状态
    centos8上使用lsblk查看块设备
    centos8环境判断当前操作系统是否虚拟机或容器
    centos8平台使用lscpu查看cpu信息
    centos8平台使用pidstat监控cpu/内存/io
    docker19.03使用数据卷
    testng对失败时截图处理
  • 原文地址:https://www.cnblogs.com/jokerbj/p/7696068.html
Copyright © 2011-2022 走看看