头图

Introduction to JQuery

JQuery is a JavaScript library, which is a shallow package of ECMScript, dom, bom, and makes it more convenient for users to operate.
Understand as a big function, many functions are encapsulated inside the function for you to use.

Digression:
The teacher said that many big companies don't use jQuery for development anymore, but some companies still use it, but the teacher said that if the company asks questions about jQuery during the interview, it can be withdrawn. . . .

But still have to learn. . .

Many of the following compare the differences between native js and jQuery and their respective usage

jQuery library contains the following functions

  • HTML selection
  • HTML element manipulation
  • CSS operations
  • HTML event function
  • JavaScript effects and functions
  • HTML DOM traversal and modification
  • AJAX

Hang up the jQuery documentation

Online use: https://www.bootcdn.cn/jquery/

Chinese document: https://jquery.cuishifeng.cn/

JQuery installation

jQuery installation is very simple, just import the jQuery library into the html, we can download it or use CDN resources.
Generally, when we download or use cdn resources, we will let us choose the jquery.js and jquery.min.js versions. The difference between them is that jquery.min.js is compressed, smaller in size, and suitable for deployment environments. While jquery is suitable for source code research, our learning of jquery should be raised to the source code level.

There are two ways to introduce

  • The first type, local introduction
    Create a new js file in the current directory, put all the native code of the official document, and then import
    Chinese document: https://www.bootcdn.cn/jquery/
  引入示例:<script src="./js/jquery.js"></script>
  • The second online introduction
    Directly introduce tags or links
引入示例:src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>

Verify that jQuery is successfully introduced

  <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>

   <!-- 本地引入 -->
   <!-- <script src="./1-jquery.3.6.0.js"></script> -->
   <script>
    //    成功打印则引入jQuery成功
       console.log($);   //function jQuery(selector, context)   
       console.log(jQuery);
       console.log($ === jQuery);  //true
   </script>

jQuery function

Call functions through "jQuery" and'$'

  • $(selector)
    Select the element that meets the conditions through the selector, and save it to the jQuery object
  • $(html fragment)
    Convert HTML fragments into Element elements, and then encapsulate them into a jQuery object
  • $(Element element)
    Convert the Element element into a jQuery object
  • $(anonymous function)--->> $(function()())
    The anonymous function is executed after the document is loaded, similar to window.onload=function(){}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./1-jquery.3.6.0.js"></script>
    <script>
        // 选择到符合条件的Element元素,将其保存到jQuery对象中
        //选择器   匿名函数$
        $(function () {
            console.log($('#parent'));  //jQuery.fn.init [div#parent]
            console.log($('.child'));//jQuery.fn.init(3) [div.child, div.child, div.child, prevObject: jQuery.fn.init(1)]
            
            
            //将html代码片段转换成Element元素,封装成一个jQuery对象
             var newChild=$('<div class="new">four</div>');
             console.log(newChild); //jQuery.fn.init [div.new]


            //element   转换成一个Jquery对象
            console.log($('div'));  //共有四个div标签
            //jQuery.fn.init(4) [div#parent, div.child, div.child, div.child, prevObject: jQuery.fn.init(1)]
        })
    </script>

</head>

<body>
    <div id="parent">
        <div class="child">one</div>
        <div class="child">two</div>
        <div class="child">three</div>
    </div>
</body>

</html>

Let's dry the rice first. . . .

The dry meal is back, and the happiness continues. . .

jquery core functions and core objects

  <script>
        //核心函数
        console.log($,typeof $);  //function jQuery(selector, context)  function
        //核心对象
        console.log($(),$() instanceof Object);  //Object{}  true

    </script>

compare native js and jQuery

Example: Get three divs through native js and jQuery and modify their background colors

Note: jQuery uses the css() method to change the style

The official documentation is pretty good
http://git.w3c0.com/jquery/136966

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <!-- 引进jQuery -->
    <script src="./1-jquery.3.6.0.js"></script>
    

    <script>


        //原生js获取dom节点并修改背景色
        window.onload = function (params) {
            //获取dom节点
            var div1 = document.getElementsByTagName('div')[0];
            var div2 = document.getElementsByClassName('two')[0];
            var div3 = document.getElementById('three')
            console.log(div1,div2,div3,'jsDom');
            //修改背景颜色
            div1.style.backgroundColor = 'red'
            div2.style.backgroundColor = 'green'
            div3.style.backgroundColor = 'pink'
            div1.style.width = '300px'
            div2.style.height = '300px'
        }



        
        // jQuery
        $(function() {  //必写入口函数,当前网页加载完成后就执行JQuery代码
            // 获取dom节点
            var div1 = $('div:first-child'); 
            var div2 = $('.two');
            var div3 = $('#three');
            console.log(div1,div2,div3);

            //div2.css是jQuery改变css样式的方法
            div2.css({
                backgroundColor:'yellow',
                width:'200px',
                height:'200px'
            })
            //追加节点   如果是想要创建并插入节点
            $(`<div class="newChild">newChild</div>`).appendTo('.parent')
        })
    </script>
</head>
<body>
    <div class="parent">
        <div></div>
        <div class="two">two</div>
        <div id="three">three</div>
    </div>
        
    
</body>
</html>

Compare the difference between native js and jquery entry functions

Summary: In native js, if you write multiple entry functions, the latter will overwrite the previous ones, but jQuery will not. It will execute them one by one.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./1-jquery.3.6.0.js"></script>

    <script>
        //原生js
       //    1.如果编写了多个入口就函数,后面的会覆盖掉前面的
        // window.onload = function(params) {
        //     alert('入口函数1');
        // }
        // window.onload = function(params) {
        //     alert('入口函数2')
        // }


        // jquery
        // 2.如果编写了多个入口文件,会依次执行,不会只执行最后一个
        $(document).ready(function (params) {
            alert('jquery 入口函数1')
        })
        $(document).ready(function (params) {
            alert('jquery 入口函数2')
        })
        $(document).ready(function (params) {
            alert('jquery 入口函数3')
        })

        // 3.jquery入口函数的写法
        // 一、
         $(document).ready(function(params) {
             alert('jquery入口函数的写法1')
         })
         //二、
         jQuery(document).ready(function(params) {
            alert('jquery入口函数的写法2')
             
         })
         //三、推荐选用这个
         $(function( ) {
            alert('jquery入口函数的写法3')
         })

         //四、
         jQuery(function(params) {
            alert('jquery入口函数的写法4')
         })
    </script>
</head>
<body>
    
</body>
</html>

jQuery object

The jQuery object is an array-like object, and the jQuery methods are all batch operations on the elements in the array-like object.

Note: The jQuery object can call the methods declared in jQuery.prototype, but ordinary Element elements cannot. When using jquery, when you get an object, you must understand whether the object is an Element element or a jQuery instance

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./1-jquery.3.6.0.js"></script>

    <script>
        // jQuery对象是类数组对象,jQuery方法都是对类数组对象中元素的批量操作.

        // 注意:jQuery对象可以调用jQuery.prototype中声明的方法,普通的Element元素则不能调用。
        // 在使用jquery的时候,拿到一个对象务必要搞明白该对象是Element元素还是jQuery实例
        $(function (params) {
            var res = $('.child').text('go');
            console.log(res)
            // go
            // go
            // go
        })
    </script>
</head>

<body>
    <div class="parent">
        <div class="child"></div>
        <div class="child"></div>
        <div class="child"></div>
    </div>
</body>

</html>

jQuery selector

jQuery selector and CSS selector are almost identical, so I won’t repeat them here.

W3C document introduction https://www.w3school.com.cn/jquery/jquery_selectors.asp

1. Basic selector

2. Level selector

3. Pseudo-class selector

4. Pseudo element selector

5. Attribute selector

Note: All selectors in jQuery start with a dollar sign: $()

  • Element selector

<div> elements in the page----->> $("div")

Example: All <div>s are hidden after the user clicks the button

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

     <script src="./1-jquery.3.6.0.js"></script>

     <script>

       // jQuery中所有选择器都以美元符号开头:$()

        //  页面加载完毕执行操作
        $(function() {
            // 绑定点击事件
            $('button').on('click',function(params) {
                // 用户点击按钮后所有<div>隐藏
                   $('div').hide()
            })
         
        })
     </script>
</head>
<body>
        <button>点点我</button>
        <div class="child">one</div>
        <div class="child">two</div>
        <div class="child">three</div>
    
</body>
</html>
  • class selector
 var child1=$('.child1')
            var button=$('button');
            button.click(function(){
                child1.hide()
 })

<button>点我点我</button>
    <div class="child1">1</div>
    <div class="child">2</div>
    <div class="child">3</div>
    <div class="child">4</div>
    <div class="child">5</div>
  • id selector
$('#child2')
  var child2=$('#child2')
            var button=$('button');
            button.click(function(){
            child2.hide()
  })
    <button>点我点我</button>
    <div class="child1">1</div>
    <div id="child2">2</div>
    <div class="child">3</div>
    <div class="child">4</div>
    <div class="child">5</div>

event binding

The event binding of jQuery is different from the Element element. You cannot use the onxxx attribute or addEventListener, but use on(), which can be understood as an encapsulation of the event binding of the Element element.

Just remember that jQuery uses the on() method to bind events, such as click events, etc.

The methods of binding events are:

  1. on(event,[selector],[data],fn) ---->> can be executed multiple times
  2. off(event,[selector],fn) --->> Unbind event
  3. one(event,[selector],fn)---->> can only be executed once
  4. trigger(event,[data]) ---->> To simulate the occurrence of an event, you can decide which node to follow the event bound to
  5. Quick binding click
  • on(event,[selector],[data],fn) ---->> can be executed multiple times
 <style>
        .child {
            width: 200px;
            height: 200px;
            border: 1px solid red;
            float: left;
            margin-left: 20px;
        }
    </style>

  <script>
        $(function () {
            
           // on 多次事件绑定
            $('.child').on('click', function (event) {
                // this--dom节点
                console.log(this)
         })
        })
    </script>


<body>
    <div class="parent">
        <div class="child">one</div>
        <div class="child">two</div>
        <div class="child">three</div>
    </div>
</body>

* off(event,[selector],fn) --->> Unbind event

 <style>
        .child {
            width: 200px;
            height: 200px;
            border: 1px solid red;
            float: left;
            margin-left: 20px;
        }
    </style>

  <script>
        $(function () {
             // 具名函数
            function handler() {
                console.log(this);
            }
            //事件绑定
            $('.child').on('click',handler);
             //事件解除绑定
             $('.child').off('click',handler)
          
        })
    </script>


<body>
    <div class="parent">
        <div class="child">one</div>
        <div class="child">two</div>
        <div class="child">three</div>
    </div>
</body>
  • one(event,[selector],fn)---->> can only be executed once
 <style>
        .child {
            width: 200px;
            height: 200px;
            border: 1px solid red;
            float: left;
            margin-left: 20px;
        }
    </style>

  <script>
        $(function () {
              //one ---->> 一次事件绑定
              $('.child').one('click', function (event) {
               // this--dom节点
              console.log(this)
              })
          
        })
    </script>


<body>
    <div class="parent">
        <div class="child">one</div>
        <div class="child">two</div>
        <div class="child">three</div>
    </div>
</body>

*trigger(event,[data]) ---->> To simulate the occurrence of an event, you can decide which node to bind the event to follow

 <style>
        .child {
            width: 200px;
            height: 200px;
            border: 1px solid red;
            float: left;
            margin-left: 20px;
        }
    </style>

  <script>
        $(function () {
               //trigger 先有一个点击事件  trigger模拟点击事件
               $('.child').on('click', function (event) {
                // this--dom节点
                console.log(this)
            // })
           // trigger 模拟事件触发
         // 触发第一个child的点击事件,载入时,直接触发了第一个孩子节点的事件
            $('.child:first-child').trigger('click')
          
        })
    </script>


<body>
    <div class="parent">
        <div class="child">one</div>
        <div class="child">two</div>
        <div class="child">three</div>
    </div>
</body>

*Quick binding

$('.child').click(function(){
       console.log(this)
})

Event type

  • click()
    The click() method is to call a function when the button click event is triggered
  • dbclick()
    When the element is double-clicked, the dbclick event will be triggered
 <style>
        
        .child {
            border: 1px solid red;
            width: 200px;
            height: 200px;
            float: left;
        }
    </style>

 <script>
        $(function () {
            // dblclick() 当双击元素时,触发事件
            $('.child').dblclick(function () {
                console.log(this)
            })
 
        })
    </script>

<body>

    <div class="parent">
        <input type="text">
        <div class="child">one</div>
        <div class="child">two</div>
        <div class="child">three</div>
    </div>
</body>

mouseenter()

When the mouse pointer passes through the element, the mouseenter event occurs

$('.child').mouseenter(function(){
       console.log(this)
})
  • mouseleave()
    When the mouse pointer leaves the element, the mouseleave event occurs
$('.child').mouseleave(function(){
                console.log(this)
})
  • mousedown()

When the mouse pointer moves over the element and the mouse button is pressed, the mousedown event occurs

$('.child').mousedown(function(){
                console.log(this)
})
  • mouseup()

When the mouse button is released on the element, the mouseup event occurs

$('.child').mouseup(function(){
                console.log(this)
})
  • hover()

The hover() method is used to simulate cursor hovering events

When the mouse moves to the element, it will trigger the designated first function (mouseenter); when the mouse moves out of this element, it will trigger the designated second function (mouseleave)

$('.child').hover(function(){
                console.log(this)
})
  • blur()
    When the element loses focus, the blur event occurs
    (The focus is lost when the input box is selected by the mouse. If you move it out and point to another location area, the focus will be lost, do you understand?)
$('input').blur(function(){
       console.log(this)
})

All of the above are mouse events

The following is the keyboard event

  • keydown()

Keyboard event: key press event

$('.child').keydown(function(){
                console.log(this)
 })
  • keyup()

Keyboard event: key up event

 $('.child').keyup(function(){
                console.log(this)
 })

Event Agent

Similar to event delegation in the DOM

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <script src="./1-jquery.3.6.0.js"></script>

    <style>
        .child {
            border: 1px solid red;
            width: 200px;
            height: 200px;
            float: left;
        }
    </style>

    <script>
        //事件代理
        $(function () {
            //由button按钮来控制三个孩子节点的触发事件
            $('body').on('click', 'button', function (event) {
                console.log(event)
            })
        })

    </script>
</head>

<body>

    <div class="parent">

        <div class="child">one</div>
        <div class="child">two</div>
        <div class="child">three</div>
    </div>

    <button>委托本按钮来办</button>

</body>

</html>

jQuery Dom operation

jQuery provides a series of APIs for manipulating DOM nodes, which are used to solve the disadvantages of DOM native APIs that are unable to perform batch operations and have poor functionality.

Insert method: append, appendTo, prepend, prependTo, after, before, insertBefore, insertAfter

Wrap method: wrap, unwrap, wrapAll, wrapInner

Replacement method: replaceWith, replaceAll

Removal method: empty, remove, detach

Cloning method: clone

  • append inserts the content into the element with the tail
  • appendTo inserts the added element into the target element

The effect is the same, the writing is different

$(function(){
     $('.child:first-child').append('<b>hihihi</b>')
     $(`<div class="newChild">newChild</div>`).appendTo('.parent')
   })


    <div class="parent">parent</div>
  • empty() Empty the child nodes of the target element without parameters
  $('.parent').empty()   //把parent的子节点全都清空,但是不会清除newChild
  • remove()
 $('.parent').remove()   //全都清空,一个不剩,包括新增节点newChild

* clone()
The default is shallow cloning, only the node is cloned without cloning the event; when the parameter is passed as true, deep cloning, and the same as the dom event, when the node is cloned, the event will also be cloned

The cloned node has the same event and style

  //    clone();默认浅克隆,只克隆节点不克隆事件;传递参数为true的时候深克隆,
            //和dom事件一样克隆节点的时候,也会克隆事件

            //浅克隆  只克隆节点 不克隆事件
            function myFun() {
                console.log('dom克隆');
            }
       
            $('.child:last-child').on('click', myFun)
    //  克隆最后一个孩子节点
            $('.child:last-child').clone(true).appendTo('.parent');

Attribute operations

1. Attributes: attr, removeAttr

2.css:addClass、removeClass、toggleClass

3. Content: html, text, val

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <script src="./1-jquery.3.6.0.js"></script>

    <style>
        .child {
            border: 1px solid red;
            width: 200px;
            height: 200px;
            float: left;
            /* background-color: rgb(123, 192, 13); */
        }
          /* 给active设置属性 */
        .active{
            background-color: rgb(33, 207, 17);
        }
    </style>

    <script>
        // jQuery入口函数
        $(function () {
            console.log($('.parent')); //jQuery.fn.init [div.parent, prevObject: jQuery.fn.init(1)]

 //可在浏览器开发者工具的Element中查看

            //attr 获取属性 一个参数代表获取属性值 两个参数代表修改当前属性值为第二个参数
            console.log($('.parent').attr('class')) //parent的类标签被去掉了

            //替换了title中的内容  one是要替换的值
            console.log($('.parent').attr('title', 'one'));


            // removeAttr  去除标签属性
            console.log( $('.parent').removeAttr('title'));//parent的title属性没得了


            //removeClass 移除类名child   并且移除样式
             $('.child').removeClass('child');//就是给child设置的样式也一起去除了


            // addClass 新增类名 
            // $('.child').addClass('active')  


            // toggleClass 切换类名 原dom有类名删除,没有类名就添加
            $('.child').toggleClass('active')

            // 使用this通过点击事件也可以切换
            $('.child').on('click', function () {
               //变换的时候 用active样式来替换
                $(this).toggleClass('active')
            })


              // 获取内容
            console.log($('.parent').html());
            console.log($('.parent').text());
            console.log($('input[type=text]').val());


        })


    </script>
</head>

<body>
    <!-- <div class="parent" title="lalalal">
        <div class="child">one</div>
        <div class="child">two</div>
        <div class="child">three</div>
    </div> -->
         输入框:<input type="text">
    <div class="parent" title="lalalal">
        <div class="child active">one</div>
        <div class="child active">two</div>
        <div class="child active">three</div>
    </div>
</body>

</html>

static method

Static methods belong to the methods defined on jQuery functions, which are directly called by jQuery or $

Array and object operations: each, map, toArray

5.1 Array and Object Operations

1.each traverses the array or object. The first parameter of the array or object to be traversed. The second parameter of the processing function


         var obj={
            name:"zhangsan",
            age:12
        }
              //遍历数组  
        $.each(obj,function(index,item){
            console.log(index,item)
              //   0 3
              //   1 4
              //   2 1
              //   3 4
              //   4 3
        })

2.toArray converts an array-like object into an array

                //toArray   将类数组对象转换为数组
            console.log($('.child').toArray());  
                //[div.child, div.child, div.child]

3.map() converts the elements in one array to another array

           //map()   返回新数组
            var arr = [1, 2, 3, 4, 5];
            var result = $.map(arr, function (index, item) {
                return index + 4;
            })
            console.log(result);  //[5, 6, 7, 8, 9]


云绮棠兮
48 声望10 粉丝

当野心追赶不上才华,便静下心来努力


下一篇 »
H5API