jQuery是继prototype之后又一个JavaScript框架,是一个快速、简洁的JavaScript库,使用户能更方便的处理HTML documents、events、实现动画效果,并且方便地为网站提供AJAX交互;jQuery能够使用户的html页保持代码和内容分离,即不用再在html中插入一堆js来调用命令了,只需定义id即可。

什么是jQuery对象:

jQuery对象就是通过jQuery包装DOM对象后产生的对象;jQuery对象是jQuery独有的,如果一个对象是jQuery对象,那么它就可以使用jQuery里的方法:$("#test).html();即获取ID为test的元素内的html代码,等同于用DOM实现:document.getElementById("test").innerHTML;虽然jQuery对象是包装DOM对象后产生的,但是jQuery无法使用DOM对象的任何方法,同理DOM对象也不能使用jQuery里的方法。

约定:如果获取的是jQuery对象,那么要在变量前面加上$。
        var $variable = jQuery 对象
        var variable = DOM 对象

基本语法$(selector).action():

使用jQuery需要先引入:   <script src="jquery-3.6.0.js"></script>

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery-3.6.0.js"></script>
</head>
<body>
<div id="div1">11111</div>
    <script>
        //jQuery //这就是jQuery对象,可以简写为$,下面写法等同
        alert(jQuery("#div1").html());
        alert($("#div1").html());
    </script>
</body>
</html>

寻找元素(重要的选择器和筛选器)

选择器

基本选择器:$("*") $("#id") $(".class") $("element") $(".class,p,div")
层级选择器:$(".outer div") $(".outer>div") $(".outer+div") $(".outer~div")
基本筛选器:$("li:first") $("li:eq(2)") $("li:even") $("li:gt(1)")
属性选择器:$('[id="div1"]') $('[alex="ss"][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()

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery-3.6.0.js"></script>
</head>
<body>
<div id="div1">hello div</div>
<div class="div"> hahhaha
    <ul>
        <li>11111</li>
        <li>22222</li>
        <li>33333</li>
        <li>44444</li>
    </ul>
</div>
<p class="p2">hello ppp</p>
<div class="outer">oooooooooooo
    <div>哈哈哈哈或
        <p class="pinner"> hello p outer</p>
    </div>
    <p class="pouter">hello ppppppppppp</p>
</div>
<p class="p3">hello pppppp33333</p>
<p class="p4">hello pppppp44444</p>
<p alex="bbb">uuuuuuu</p>
<p alex="www">rrrrrrrrr</p>
<input type="text">
<input type="button">
<script>
    //基本选择器
    $("*").css("color","red").css("background-color","gray");
    //通配符选择器,链式编程
    $("div").css("color","blue"); //标签选择器
    $("#div1").css("color","blue");//id选择器
    $(".p2").css("color","blue"); //class选择器
    $(".div1,#p2").css("color","blue"); //并列选择器

    //层级选择器
    $(".outer p").css("color","yellow");//后代选择器,选择pinner和pouter
    $(".outer>p").css("color","red");//子代选择器,只选pouter
    $(".outer+p").css("color","black");//毗邻选择器,只选p3
    $(".outer~p").css("color","white");//向下找兄弟,选择p3和p4

    //基本筛选器,通过冒号后加表达式
    $(".div li:first").css("color","green");//选择li的第一个元素
    $(".div li:last").css("color","green");//选择li的最后一个元素
    $(".div li:eq(2)").css("color","green");//索引等于2的li
    $(".div li:lt(2)").css("color","green");//索引小于2的li
    $(".div li:gt(2)").css("color","green");//索引大于2的li

    //属性选择器
    $("[alex]").css("color","#12eaea");  //根据属性alex选择,alex="bbb"和alex="www"都选择
    $("[alex='bbb']").css("color","#12eaea");//选择alex=’bbb'
    $("[type='button'").css("width",'50px');//通过属性选择
    $(":button").css("width",'100px');//上面写法的简写,只适用input标签

    //筛选器
    //过滤筛选器

    //查找筛选器
    $(".outer").children().css("color","#E89898");//children只在子代找
    $(".outer").find("p").css("color","#a0EF98");//find在所有后代中找
    $(".p2").next().css("color","red");//只找p2的下一个兄弟
    $(".p2").nextAll().css("color","red");//找p2之后的所有兄弟
    $(".p2").nextUntil(".p4").css("color","red");//查找区间,从p2下一个兄弟一直到p4,但不包括p4
    $(".p4").prev().css("color","red");//只找p4的上一个兄弟,即p3
    $(".p4").prevAll().css("color","red");//找p4的所有上面的兄弟
    $(".p4").prevUntil(".p2").css("color","red");//查找区间,p4到p2之间的兄弟,不包括p2
    $(".p2").parent().css("color","red");//找p2的父亲
    $(".p2").parents().css("color","red");//找p2的所有父辈,包括父亲,爷爷及以上,直到body
    $(".pinner").parentsUntil(".outer").css("color","red");//区间查找,找到outer父标签,但不包括。
    $(".p2").siblings().css("color","red");//找兄弟标签,不包括自身

</script>
</body>
</html>

点击菜单打开关闭示例:

 

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery-3.6.0.js"></script>
    <script>
        function show(self) {
            $(self).next().removeClass("hide");
            $(self).parent().siblings().children(".con").addClass("hide");
        }
    </script>
    <style>
        .menu{
            height: 500px;
            width: 30%;
            background-color: #b4b4b4;
            float: left;
        }
        .content{
            height: 500px;
            width: 70%;
            background-color: #84a42b;
            float: left;
        }
        .title{
            line-height: 50px;
            background-color: #336699;
            color: red;
        }
        .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>菜单一111111</div>
                <div>菜单一222222</div>
                <div>菜单一333333</div>
            </div>
        </div>
        <div class="item">
            <div class="title" onclick="show(this);">菜单二</div>
            <div class="con hide">
                <div>菜单二111111</div>
                <div>菜单二222222</div>
                <div>菜单二333333</div>
            </div>
        </div>
        <div class="item">
            <div class="title" onclick="show(this);">菜单三</div>
            <div class="con hide">
                <div>菜单三111111</div>
                <div>菜单三222222</div>
                <div>菜单三333333</div>
            </div>
        </div>
    </div>
    <div class="content"></div>

</div>
<script>

</script>
</body>
</html>

Tab菜单切换:

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery-3.6.0.js"></script>
    <style>
        *{
            margin: 0;
            padding: 0;

        }
        .tab_outer{
            margin: 0 auto;
            width: 70%;
        }
        .menu{
            background-color: #b4b4b4;
            line-height: 40px;
        }
        .menu li{
            display: inline-block;
        }
        .content{
            background-color: #84a42b;
            border: 1px solid greenyellow;
            height: 300px;
        }
        .hide{
            display: none;
        }
        .current{
            background-color: #c0cddf;
            color: yellow;
            border-top: solid 1px rebeccapurple;
        }
    </style>
</head>
<body>
    <div class="tab_outer">
        <ul class="menu">
            <li xxx="c1" class="current" onclick="tab(this);">Tab页一</li>
            <li xxx="c2" onclick="tab(this);">Tab页二</li>
            <li xxx="c3" onclick="tab(this);">Tab页三</li>
        </ul>
        <div class="content">
            <div id="c1">页一内容</div>
            <div id="c2" class="hide">页二内容</div>
            <div id="c3" class="hide">页三内容</div>
        </div>
    </div>
<script>
    function tab(self) {
        // $(self).addClass("current");
        // $(self).siblings().removeClass("current");
        $(self).addClass("current").siblings().removeClass("current")
        var s ="#" + $(self).attr("xxx");
        $(s).removeClass("hide").siblings().addClass("hide");

    }
</script>
</body>
</html>

 属性操作:

attr()与removeAttr():

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery-3.6.0.js"></script>
</head>
<body>
<input id="ck" type="checkbox">
<script>
    $("#ck").attr("id");     //取属性值
    $("#ck").attr("id","eee"); //修改属性值
    $("#eee").attr("checked","true"); //修改checked值为true,即选中
    $("#eee").removeAttr("checked"); //删除checked属性,相当于取默认值,即false
    
</script>
</body>
</html>

 prop()与removeProp()

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery-3.6.0.js"></script>
</head>
<body>
<input id="ck" type="checkbox" checked="true">
<script>
    $("#ck").attr("id");     //取属性值
    $("#ck").attr("id","eee"); //修改属性值
    $("#eee").attr("checked","true"); //修改checked值为true,,没有checked属性就添加,即选中
    $("#eee").removeAttr("checked"); //删除checked属性,相当于取默认值,即false

    var s = $("#ck").prop("id"); //取属性值
    $("#ck").prop("id","wes"); //修改属性值
    $("#wes").prop("checked","true");//修改checked值为true,,没有checked属性就添加,即选中
    $("#wes").removeProp("checked","false");
    //删除checked属性,相当于取默认值,即false ,这个测试没成功
</script>
</body>
</html>

关于each()方法,遍历:

li = [10,20,30,40];
        $.each(li,function (i,x) {
            console.log(i,x);
        //each方法,第一个参数是要遍历的数组,第二个参数是一个函数
        //即要使用这个函数对遍历进行处理,这个函数的第一个参数i数索引值,第二个参数x是值
       })
        dic = {name:"nnnnn",sex:"male"};
        $.each(dic,function (i,x) {
            console.log(i,x);
        // 遍历字典,i为key,x为value
        })

 each方法实现反选功能:

html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery-3.6.0.js"></script>

</head>
<body>
<input type="button" value="all" onclick="selectall();">
<input type="button" value="cancelall" onclick="cancelall();">
<input type="button" value="reverse" onclick="reverse();">
<hr>
<table>
    <tr>
        <td><input type="checkbox"></td>
        <td>1111111</td>
    </tr>
    <tr>
        <td><input type="checkbox"></td>
        <td>222222</td>
    </tr>
    <tr>
        <td><input type="checkbox"></td>
        <td>33333333</td>
    </tr>
</table>
<script>
    li = [10,20,30,40];
    $.each(li,function (i,x) {
        console.log(i,x);
    //each方法,第一个参数是要遍历的数组,第二个参数是一个函数
    //即要使用这个函数对遍历进行处理,这个函数的第一个参数i数索引值,第二个参数x是值
   })
    dic = {name:"nnnnn",sex:"male"};
    $.each(dic,function (i,x) {
        console.log(i,x);
    // 遍历字典,i为key,x为value
    })
    $("table tr").each(function () {  //each的另一种用法
        console.log($(this).html());//列出每个tr标签
    })
    function selectall() {
        $("table :checkbox").each(function () {
            $(this).attr("checked","true");
        })
    }
    function cancelall() {
        $("table :checkbox").each(function () {
            $(this).removeAttr("checked");
        })
    }
    function reverse() {
        $("table :checkbox").each(function () {
            // if($(this).attr("checked")){
            //     $(this).removeAttr("checked");
            // }else{
            //     $(this).attr("checked","true");
            // }  //上面的attr使用反选有问题
            if($(this).prop("checked")){
                $(this).removeProp("checked");
            }else{
                $(this).prop("checked","true");
            }
        })
    }
</script>
</body>
</html>

插入元素:

append与appendTo方法:注意调用的主体,方法的参数。

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery-3.6.0.js"></script>
</head>
<body>
<div id="div1">
    <p>hello 11111</p>
</div>
<p>fdsafsafsda</p>
<p class="p1">hello pppppp</p>
<script>
    var ele = $(".p1");
    // $("#div1").append(ele);
    //append()方法在元素中插入元素,即作为孩子插入,在最后孩子后插入
    //结果是在<p>hello 11111</p>后添加<p class="p1">hello pppppp</p>
    //测试结果显示:append实际上是移动,将<p class="p1">hello pppppp</p>移动到<p>hello 11111</p>后
    ele.appendTo($("#div1"));
    //ele元素移动到$("#div1")标签中,作为最后一个孩子
</script>
</body>
</html>

类似的prepend和prependTo方法,是在第一个孩子前插入。

前面四个都是内部插入。

外部插入:after()、before(),这两个方法是在元素同级的后面或前面插入,即成为后或前相邻的兄弟,insertAfter()、insertBefore(),这两个方法的效果同两个方法,不同的是调用的主体。
A.after(S)在A元素后插入S元素,A.before(S),在A元素前插入S元素
S.insertAfter(A),将S插入在A的后面,S.insertBefore(A),将S插入在A的前面。

复制:clone()方法,删除:remove()方法,清空:empty()方法

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery-3.6.0.js"></script>
</head>
<body>
<div id="outer">
    <div class="item">
        <input type="text">
        <input type="button" value="+" onclick="fun1(this);">
    </div>
</div>
<p>ooooooooooooooooooo</p>
<hr>
<div class="div2">
    <p>hhhhhhhhhhhhhhhhh</p>
</div>
<script>
    function fun1(self) {
        var clone_t = $(self).parent().clone();
        clone_t.children(":button").val("-").attr("onclick","fun2(this)");
        $("#outer").append(clone_t);
    }
    function fun2(self) {
        $(self).parent().remove();//删除元素
        //相对应的,有一个empty()方法,是清空的意思,是清空元素中内容,而元素还在

    }
    $(".div2").remove();
    // $(".div2").empty();
</script>
</body>
</html>

remove()后:

empty()后:

 

 

后台管理的页面布局示例:

position:absolute,定位时可以定位到右下角,滑轮滚动时,跟着滑动,不固定。
利用position:absolute + overflow:auto
获取滚轮滚动的高度:$('body').scrollTop()

 左边菜单跟随滚轮滑动,内容的改变而选择或取消:

<!--<!DOCTYPE html>  &lt;!&ndash;如果加上这一句,scrollTop就不好用&ndash;&gt;-->
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery-3.6.0.js"></script>
    <style>
        .menu{
            position: absolute;
            left: 200px;
            top:48px;
            bottom:0;
            width:120px;
            border: 1px solid red;
        }
        .menu a{
            display: block;
        }
        .activemenu{
            background-color: #336699;
            color: white;
        }
        .guding{
            position: fixed;
            top:0;
        }
    </style>
</head>
<!--<body style="margin: 0;" onscroll="gundong();">-->
<body style="margin: 0;">
    <div style="height: 48px;background-color: #303a40"></div>
    <div id="menu" class="menu" >
        <a timu="1">菜单一</a>
        <a timu="2">菜单二</a>
        <a timu="3">菜单三</a>
        <a timu="4">菜单四</a>
    </div>
    <div id="content" style="position: absolute;left: 320px;right: 100px;bottom: 0;top: 48px; border: 1px solid gray;">
        <div zhang="1" style="height: 500px;background-color: #336699">菜单一内容</div>
        <div zhang="2" style="height: 900px;background-color: green">菜单二内容</div>
        <div zhang="3" style="height: 1000px;background-color: rebeccapurple">菜单三内容</div>
        <div zhang="4" style="height: 800px;background-color: greenyellow">菜单四内容</div>
    </div>
    <div onclick="gotop();" style="cursor:pointer;position: fixed;right: 0;bottom: 0;width: 50px;height: 50px;background-color: gray;color: white;border: 1px solid red;">返回顶部</div>
<script>
    function gotop(){
        $(window).scrollTop(0);
    }
    window.onscroll = function gundong() {

        var scrollTop_t = $("body").scrollTop();
        //scrollTop()要想起作用,第一行不能有<!DOCTYPE html>
        //scrollTop()加上一个参数,就是设置滚轮的高度,否则是获取
        if(scrollTop_t>48){
            $("#menu").addClass("guding");
            //向上滚动48px,就给menu加一个guding的类型,将菜单栏固定住
        }else{
            $("#menu").removeClass("guding");
            $("#menu a").removeClass("activemenu");//当重新滚动到最顶端时,所有菜单选定的取消,即菜单一取消
        }
        $("#content").children().each(function () {
            var eleTop = $(this).offset().top;
            var winTop = eleTop - scrollTop_t;
            var winBottomTop = eleTop + $(this).height() - scrollTop_t;
            var docHeight = $(document).height();
            var winHeight = $(window).height();
            if(docHeight - winHeight == scrollTop_t){
                $("#menu a:last").addClass("activemenu").siblings().removeClass("activemenu");
            }else {
                if(winTop<=0 && winBottomTop>0){
                //当前内容对应的菜单应该被选中
                var a = $(this).attr("zhang");
                $("#menu a[timu='" +a+"']").addClass("activemenu").siblings().removeClass("activemenu");
                return;
            }
            }

        })
    }
    //offset()获取当前元素距离文档顶部的距离
    //height()获取当前元素自身的高度
    //innerHeight()获取元素内部区域高度(包括补白、不包括边框)自身高度+padding
    //outerHeight()获取元素外部高度(默认包括补白和边框),设置为true时,计算边距在内
    //outerHeight(false) 自身+padding+border,outerHeight(true) 自身+padding+border+margin
    //整个文档的高度=document高度,$(document).height()
    //窗口的高度 $(window).height
    //滚动的高度
</script>
</body>
</html>

更多推荐

前端技术——7——jQuery