jQuery学习

4 篇文章 0 订阅
2 篇文章 0 订阅

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)") //选择索引为2的标签
$("li:even") //选择索引为偶数的标签
$("li:gt(1)") //选择索引大于1的标签,不包括索引1.
属性选择器 
$('[id="div1"]')   $('[alex="sb"][id]')
表单选择器    
$("[type='text']")----->$(":text")         注意只适用于input标签  : $("input:checked")
实例之左侧菜单
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery-3.3.1.min.js"></script>
    <style>
        .outer{
            height: 500px;
            width: 100%;
        }
        .menu{
            float: left;
            width: 10%;
            height: 500px;
            background: lightseagreen;
        }
        .content{
            float: left;
            width: 90%;
            height: 500px;
            background:wheat;
        }
        .title{
            color: white;
            height: 20px;
            background: aqua;
            font-size: 15px;
            text-align: center;
        }
        .hide{
            display: none;
        }
        .con{
            text-align: center;
        }
    </style>
</head>
<body>
<div class="outer">
    <div class="menu">

        <div class="item">
            <div class="title" οnclick=show(this)>菜单一</div>
            <div class="con">
                <div>1</div>
                <div>2</div>
                <div>3</div>
            </div>
        </div>

        <div class="item">
            <div class="title" οnclick=show(this)>菜单二</div>
            <div class="con hide">
                <div>1</div>
                <div>2</div>
                <div>3</div>
            </div>
        </div>

        <div class="item">
            <div class="title" οnclick=show(this)>菜单三</div>
            <div class="con hide">
                <div>1</div>
                <div>2</div>
                <div>3</div>
            </div>
        </div>

    </div>

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

<script>

    function show(self) {
        $(self).next().removeClass('hide');
        $(self).parent().siblings().children('.con').addClass('hide')
    }

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

筛选器

过滤筛选器(与上面的基本筛选器一样的功能)

$("li").eq(2)  $("li").first() $("li").last()
查找筛选器
$("div").children(".test")  // 子代选择器,只能在子代里寻找   
$("div").find(".test")  //后代选择器,可以找到所有后代
     
                          
 $(".test").next()  //选择下一个标签
$(".test").nextAll()   //选择下面所有的标签
 $(".test").nextUntil() //选择下面的标签,直到until里的指定标签,不包括until里的标签
          
                 
$("div").prev()  //选择上一个标签,其余与next类似
$("div").prevAll()  
$("div").prevUntil()   
                        
$(".test").parent()  //选择父标签
$(".test").parents()  //一直往外选择父标签,直到html
$(".test").parentUntil() //选择父标签,直到until指定的标签为止,不包括until里的

 $("div").siblings() //选择所以同胞标签

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

属性操作

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery-3.3.1.min.js"></script>
</head>
<body>

<p con="p1"></p>

<input type="checkbox" id="c1">not checked
<input type="checkbox" id="c2" checked>checked

<script>

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

    console.log($('p').attr('con'))//p1,当只有一个参数时获得属性con的值
    console.log($('p').attr('con','p2'))//当有两个参数时,就是设置属性con='p2'
    console.log($('p').prop('con'))//undefined,prop找不到自定义的属性con

    console.log($('#c1').attr('checked'))//undefined
    console.log($('#c2').attr('checked'))//checked
    console.log($('#c1').prop('checked'))//false
    console.log($('#c2').prop('checked'))//true
</script>
</body>
</html>

注意:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery-3.3.1.min.js"></script>
</head>
<body>

<p con="p1"></p>

<input type="checkbox" id="c1">not checked
<input type="checkbox" id="c2" checked>checked

<script>

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

    console.log($('p').attr('con'))//p1,当只有一个参数时获得属性con的值
    console.log($('p').attr('con','p2'))//当有两个参数时,就是设置属性con='p2'
    console.log($('p').prop('con'))//undefined,prop找不到自定义的属性con

    console.log($('#c1').attr('checked'))//undefined
    console.log($('#c2').attr('checked'))//checked
    console.log($('#c1').prop('checked'))//false
    console.log($('#c2').prop('checked'))//true
</script>
</body>
</html>
实例之全反选
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery-3.3.1.min.js"></script>
</head>
<body>
<table border="1px" cellpadding="15px">
    <tr>
        <td><input type="checkbox"></td>
        <td>111</td>
        <td>111</td>
        <td>111</td>
    </tr>
        <tr>
        <td><input type="checkbox"></td>
        <td>222</td>
        <td>222</td>
        <td>222</td>
    </tr>
        <tr>
        <td><input type="checkbox"></td>
        <td>333</td>
        <td>333</td>
        <td>333</td>
    </tr>
        <tr>
        <td colspan="4" style="text-align:center">
            <button οnclick="selectall()">全选</button>
            <button οnclick="cancelall()">取消</button>
            <button οnclick="reverse()">反选</button>
        </td>
    </tr>
</table>
<script>

    function selectall() {
        $(':checkbox').prop('checked',true);

    }

    function cancelall() {
        $(':checkbox').prop('checked',false);
    }

    function reverse() {
        $(':checkbox').each(function () {
           $(this).prop('checked',!$(this).prop('checked'))
        })

    }


    //jQueryd的两种循环方式


    li=[10,9,8,7,6,5,4];
    dic={'name':'alex','age':24}
    $.each(li,function (i,x) {
        console.log(i,x);
    })
    $.each(dic,function (i,x) {
        console.log(i,x)
    })


    $('tr').each(function ()
    {
     console.log($(this).html() );
    })


</script>
</body>
</html>
实例之模态对话框
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery-3.3.1.min.js"></script>
    <style>
        .div1{
            background: white;
        }
        .div2{
            background: #b4b4b4;
            opacity: 0.5;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
        }
        .div3{
            position: absolute;
            width: 300px;
            height: 150px;
            margin-top: 15%;
            margin-left: 40%;
            background: aqua;
        }
        .hide{
            display: none;
        }
    </style>
</head>
<body>
<div class="div1">this is content
    <button οnclick="show(this)">show</button>
</div>
<div class="div2 hide"></div>
<div class="div3 hide"><button οnclick="hide(this)">hide</button></div>
<script>

function show(self) {
    $(self).parent().siblings().removeClass('hide');
}

function hide(self) {
    $(self).parent().addClass('hide').prev().addClass('hide');
}
</script>
</body>
</html>

文档处理

//创建一个标签对象
    $("<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>
    <script src="jquery-3.3.1.min.js"></script>
</head>
<body>

<div class="outer">
    <div class="inner">
        <p class="inp">this is inner p</p>
    </div>
    <p class="outp"> this is out p</p>
</div>

<div class="bro1">
    <span>hello span</span>
</div>

<div class="bro2">this is bro2</div>

<script>
    //内部插入
    // $('.outer').append('<h1>hello world</h1>')//append追加在后面
    var $ele=$('<p>');//创建新标签
    $ele.html('hello this is new p');
    $ele.css('color','red')
    // $ele.appendTo($('.inner'));
    // $('.bro1').prepend($ele);                 //prepend追加在前面
    // $('<h1>hello span</h1>').prependTo($('.bro1'));


    //外部插入(用法与内部插入类似)
    // $('.bro2').after($ele);
    // $('.bro2').before($ele);
    // $ele.insertAfter($('.bro2'));
    // $ele.insertBefore($('.bro2'));

    //替换
    // $('.bro1 span').replaceWith($ele)

    //删除
    // $('.outer').empty();//保留outer标签,清除内部标签
    // $('.outer').remove();//把整个outer标签删除

    //复制
    // var $ele1=$('.bro1').clone();
    // $ele1.insertAfter($('.bro2'));

</script>
</body>
</html>
实例之复制样式条
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery-3.3.1.min.js"></script>
</head>
<body>
<div class="item">
    <button οnclick="add(this)">+</button>
    <input type="text">
</div>
<script>

    function add(self) {
        var $ele=$(self).parent().clone();
        $ele.children('button').html('-').attr('onclick','sub(this)');
        $ele.insertAfter($('.item:last'))
    }

    function sub(self) {
        $(self).parent().remove();
    }
</script>
</body>
</html>

css操作

CSS
        $("").css(name|pro|[,val|fn])
    位置
        $("").offset([coordinates])
        $("").position()
        $("").scrollTop([val])
        $("").scrollLeft([val])
    尺寸
        $("").height([val|fn])
        $("").width([val|fn])
        $("").innerHeight()
        $("").innerWidth()
        $("").outerHeight([soptions])
        $("").outerWidth([options])
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery-3.3.1.min.js"></script>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        .div1,.div2,.div3{
            width:200px;
            height: 200px;
        }
        .div1{
            background: aqua;
        }
        .div2{
            background: lightpink;
        }
        .div3{
            background: lightseagreen;
            padding: 10px;
            border: 5px solid greenyellow;
        }
    </style>
</head>
<body>
<div class="div1"></div>

<div style="position: relative">
    <div class="div2"></div>
</div>
<div class="div3"></div>
<script>

    //offset()是相对窗口的位置
    console.log($('.div1').offset().top);//0
    console.log($('.div1').offset().left);//0
    console.log($('.div2').offset().top);//200
    console.log($('.div2').offset().left);//0

    //position()是相对已经定位的父标签的位置
    console.log($('.div1').position().top);//0
    console.log($('.div1').position().left);//0
    console.log($('.div2').position().top);//0
    console.log($('.div2').position().left);//0

    console.log($('.div3').width());//200px,只是文本框的高和宽,不包括margin和padding
    console.log($('.div3').height());//200px,可以在括号里加入参数调整

    console.log($('.div3').innerHeight());//220px,包括padding,不包括margin
    console.log($('.div3').innerWidth());//220px,可以在括号里加入参数调整包括padding在内的长宽

    console.log($('.div3').outerHeight());//230px,包括margin
    console.log($('.div3').outerWidth());//230px,加入参数修改margin在内的长宽

</script>
</body>
</html>
实例返回顶部
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery-3.3.1.min.js"></script>
    <style>
        .div1{
            width: 50%;
            height:200px;
            background: aquamarine;
            overflow:auto;
        }
        .div2{
            width: 100%;
            height: 1000px;
            background: lightpink;
        }
        .div3{
            width: 100px;
            height: 50px;
            text-align: center;
            line-height: 50px;
            position: fixed;
            right: 20px;
            bottom: 20px;
            background: #b4b4b4;
        }
        .hide{
            display: none;
        }
    </style>
</head>
<body>
<div class="div1">
    <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">
    <button οnclick="divreturn()">返回顶部</button>
</div>
<div class="div3 hide" οnclick="returntop()">返回顶部</div>
<script>
    window.οnscrοll=function (ev) {                  //window.onscroll会检测滚动条的滚动

        console.log($(window).scrollTop())           //$(window).scrollTop()会显示滑条到顶部的距离

        if($(window).scrollTop()>100)                //当与顶部距离大于100时显示返回顶部的块,否则隐藏
        {
            $('.div3').removeClass('hide');
        }
        else
        {
            $('.div3').addClass('hide');
        }
    }

    function returntop() {

        $(window).scrollTop(0); //scrollTop()里可以加参数,表示到顶部的距离,scrollTop(0)即表示返回到顶部
    }

    function divreturn() {
        $('.div1').scrollTop(0); //不仅window可以用scrollTop(),标签也可以
    }
    
    //scrollLeft()就是下面的滚动条,使用方法也scrollTop()一样
    
</script>
</body>
</html>

事件

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

事件处理
    $("").on(eve,[selector],[data],fn)  // 在选择元素上绑定一个或多个事件的事件处理函数。

    //  .on的selector参数是筛选出调用.on方法的dom元素的指定子元素,如:
    //  $('ul').on('click', 'li', function(){console.log('click');})就是筛选出ul下的li给其绑定
    //  click事件;

    [selector]参数的好处:
        好处在于.on方法为动态添加的元素也能绑上指定事件;如:

        //$('ul li').on('click', function(){console.log('click');})的绑定方式和
        //$('ul li').bind('click', function(){console.log('click');})一样;我通过js给ul添加了一个
        //li:$('ul').append('<li>js new li<li>');这个新加的li是不会被绑上click事件的

        //但是用$('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)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery-3.3.1.min.js"></script>
    <script>
            //$('ul li').html('hello world');//直接写这一句是不行的
          ready类似于js的.onload
        // $('ul li').ready(function () {
        //     $('ul li').html('hello world');
        // })
        //简写形式为
        // $(function () {
        //     $('ul li').html('hello world');
        // })
    </script>
</head>
<body>
<ul>
    <li>111</li>
    <li>222</li>
    <li>333</li>
    <li>444</li>
</ul>
<script>
//事件绑定
    //简写形式
    // $('ul li').click(function () {
    //     var $ele=$('<li>');
    //     $ele.html(($('ul li').length+1)*111)
    //     $('ul').append($ele);
    // })

    //完整的绑定为
    // $('ul li').bind('click',function () {
    //     var $ele=$('<li>');
    //     $ele.html(($('ul li').length+1)*111)
    //     $('ul').append($ele);
    // })

    // //解绑
    // $('ul li').unbind('click')
    //以上的绑定事件发现,在点击增加的li时并不会触发函数,函数只绑定了原来的那几个li,所以需要用事件委托on

//事件委托
    //形式$(标签).on(事件,需要被绑定的标签,参数(非必须),函数)

    $('ul').on('click','li',function () {
        var $ele=$('<li>');
        $ele.html(($('ul li').length+1)*111)
        $('ul').append($ele);
    })
    //好处在于.on方法为动态添加的元素也能绑上指定事件
</script>
</body>
</html>

动画效果

显示隐藏
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery-3.3.1.min.js"></script>
    <script>

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

//用于切换被选元素的 hide() 与 show() 方法。
    $("#toggle").click(function () {
        $("p").toggle();
    });
})

    </script>
    <link type="text/css" rel="stylesheet" href="style.css">
</head>
<body>


    <p>hello</p>
    <button id="hide">隐藏</button>
    <button id="show">显示</button>
    <button id="toggle">切换</button>

</body>
</html>
滑动
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery-3.3.1.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>
淡入淡出
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery-3.3.1.min.js"></script>
    <script>
    $(document).ready(function(){
   $("#in").click(function(){
       $("#id1").fadeIn(1000);


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

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


   });
    $("#fadeto").click(function(){
       $("#id1").fadeTo(1000,0.4);

   });
});



    </script>

</head>
<body>
      <button id="in">fadein</button>
      <button id="out">fadeout</button>
      <button id="toggle">fadetoggle</button>
      <button id="fadeto">fadeto</button>

      <div id="id1" style="display:none; width: 80px;height: 80px;background-color: blueviolet"></div>

</body>
</html>
回调函数
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery-3.3.1.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>

扩展方法 (插件机制)

用JQuery写插件时,最核心的方两个方法
<script>
    
$.extend(object)      //为JQuery 添加一个静态方法。
$.fn.extend(object)   //为JQuery实例添加一个方法。


    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>

















  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值