jQuery-01: basic syntax operation

1. Entry function

  • Js native entry function:
    window.onload = function(){ }​
  • Jq entry function:
    Abbreviation: $(function() {})
    Standard: $(document) ready(function () { })

The difference between jq entry function and native entry function

  • (1) Different execution times:
    Native: only one entry function can be registered
    jq: you can register multiple
  • (2) Different timing:
    Native: the DOM tree + external resource path is loaded before execution
    jq: execute after the DOM tree is loaded
        // 1.Js native entry function: dom tree + external resources
        window.onload = function () {
            console.log('111-Native entry function');
        }


        // 2.jq entry function: execute after the dom tree is loaded  
        //1. Abbreviations
        $(function () {
            console.log('222-JQ Entry function');
        })
        //2. Standards
        $(document).ready(function () {
            console.log('333-JQ Entry function');
        })

2.DOM object and JQ object acquisition and mutual conversion

    //1.DOM object: an object obtained using dom native syntax
    let box = document.querySelector('#box')
    console.log(box); //dom object

    // dom object to jq object: $(dom object)
    console.log($(box)); //jQuery.fn.init(1)

    // 2.jq object object obtained using jq syntax (jq object is essentially a pseudo array)
    let $box = $('#box')
    console.log($box); //jQuery.fn.init(1)

    //jq object to DOM object: $(jq object) [subscript]
    console.log($box[0]); //dom object

        1. $ Is a function
        2. $ And jQuery Complete equivalence:Usually use $All places can be replaced with jQuery 
            $ === jQuery
        3.1 The parameter is a selector, and the function is to obtain jq object
            $('selector')
        3.2 Parameters are functions,Function is the entry function
            $(function(){})
        3.3 Parameter is dom object,The function is dom turn jq
            $(dom object)

3-jQuery syntax: query operation

3.1. Basic selector

nameusagedescribe
ID Selector $('#id');Gets the element with the specified ID
Class selector $('.class');Get elements of the same class
tag chooser $('div');Gets all elements of the same class of labels
Union selector$('div,p,li');Use commas to separate as long as one of the conditions is met.
Intersection selector$('div.redClass');Get div element with class redClass
  • Conclusion: it is as like as two peas of css.

3.1 - hierarchy selector

nameusagedescribe
Progeny selector$('ul > li');Use the - sign to get the elements of the child level. Note that the elements of the child level are not obtained
Descendant Selectors $('ul li');Use a space to represent the descendant selector to obtain the selected value under ul

3.3 - filter selector

  • These selectors have colons:
nameusagedescribe
:eq(index)$('li:eq(2)').css('color', 'red');Among the obtained li elements, select the element with index number 2, and the index number starts from 0.
:odd$('li:odd').css('color', 'red');Among the obtained li elements, select the elements with odd index numbers
:even$('li:even').css('color', 'red');Among the obtained li elements, select the element with an even index number

3.4 CSS attribute operation

css style operation of jq
Get: $() css('style name ')
Setting: $() css('style name ', style value)

<script src="jquery-1.12.4.js"></script>
    <script>
        $(function(){
            /* 
            1.Review the native DOM operations css style properties - > intrinsic object assignment syntax
                Query operations: element objects style. Attribute name
                Setting operations: element objects style. Attribute name = value

            1.1 Notes on native syntax
                a. You can only get in line, not out of line
                b. Gets the string type with units
                c. You can get or set

            2.jq Syntax operation css Style - > call method
                Query css Style: $() css('attribute name ')
                Set css Style: $() css('attribute name ', attribute value)

                * It can be operated both inside and outside the line (value + assignment) - > getComputedStyle() is used at the bottom layer

            3.summary
                (1)Method unification: getting and setting method names are the same. Different parameters have different functions
                (2)Implicit iteration: covert traversal
                    * a.Getting a class will only get the first one by default
                    * b.Set the class to iterate implicitly
            */


            /*jq Registration event 
            (1)Native DOM registration event essence: object attribute assignment syntax DOM event source onclick = function(){}
            (2)jq Register event essence: call function $() Click (event handler);
            */

            //1. Query css Style
            $('#btn1').click(function(){
                //1.1 only one element
                console.log($('#box').css('width'));
                //1.2 there are multiple elements, and the first one is obtained by default
                console.log($('.one').css('width'));
                
            });

            //2. Get css Style
            $('#btn2').click(function(){
                //2.1 only one element
                $('#box').css('width','300px');

                //2.2 multiple elements: implicit iteration: covert traversal
                $('.one').css('width','500px');
            });
        });
    </script>

3.5-html attribute operation

    	jquery Element attribute actions in
        a.Text content
            $().text()
            $().html()
        b.Standard properties+Custom properties
            obtain/set up: $().attr()
            Remove:   $().removeAttr()
<script>
    /*Knowledge points in this section: html attribute operation
        1.Review webapi action element attributes
            a.Text content
                innerText:Get text (including child element text)
                innerHTML:Get content (text and labels)
            b.html Standard properties
                href : a Tag name link
                src:  img Label link
            c.html Custom properties
                Element getAttribute('attribute name ')
                Element setAttribute('attribute name ', attribute value)
                Element removeAttribute('attribute name ')
        
        2.jquery Element attribute actions in
            a.Text content
                $().text()
                $().html()
            b.Standard attribute + custom attribute
                Get / set: $() attr()
                Remove: $() removeAttr()
    */

    //1. Text content

    //1.1 acquisition
    //text(): get the text of the element (including child elements)
    console.log($('#box').text());
    //html(): get the content of the element (text and label)
    console.log($('#box').html());

    //1.2 setting
    //text(): unable to parse label
    $('#box').text('<a href="#"> I am a fan of the monitor < / a > ';
    //html(): tags can be parsed
    $('#box').html('<a href="#"> I am a fan of the monitor < / a > ';

    //2.html attributes

    //2.1 acquisition
    console.log($('#box').attr('aaa'));
    console.log($('a').attr('href'));
    console.log($('img').attr('src'));

    //2.2 setting
    $('#box').attr('aaa ',' I love monitor ')// In line custom attributes can be modified if they exist
    $('#box').attr('bbb ',' I love brother Kun ')// If the in-line custom attribute does not exist, it is added dynamically

    $('a').attr('href','http://www.itheima.com');
    $('img').attr('src','./images/0002.jpg');

    //2.3 removal
    $('a').removeAttr('href');
    $('#box').removeAttr('aaa');

</script>

3.6 - form element attribute operation

jquery syntax:
obtain:
$(selector) val( )
Boolean type attribute: $() prop(‘disabled’)
set up:
$(selector) val('text ')
Boolean type attribute: $() prop(‘disabled’,true)

<script>
        $(function(){
            /* 
            1.Review the native dom action form element properties
                a.Get text: value attribute
                b.Boolean type attribute: disabled checked selected

            2.jquery grammar
                a.Get text: $() val()
                b.Boolean type attribute: $() prop()
            */

            //1. Form text operation
            //1.1 acquisition
            console.log($('input:eq(0)').val());
            //1.2 setting
            $('input:eq(0)').val('Dark horse programmer');

            //2. Boolean type attribute operation

            //2.1 acquisition
            console.log($('input:eq(0)').prop('disabled'));
            //2.2 setting console log($('input:eq(0)'). prop('disabled',true));
           
         
    });
</script>

4. Case: switch light

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

<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>

<body>
    <button id="btn">Turn off the lights</button>

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

    <script>
        /* Idea:
        Click the button: 
            If the text is off, (1) set the body color black (2) set your own text: turn on the light
            Otherwise, turn on the light: (1) set the default color of body color (2) set your own text: turn off the light     
        */

        $('#btn').on( 'click' , function(){
            /*  this And $(this) 
            this : dom Object, only dom syntax can be used
            $(this) : jq Object, can only use jq syntax
            */
            console.log( this )
            console.log( $(this) )
            if( $(this).text() == 'Turn off the lights' ){
                $('body').css('backgroundColor','#000')
                $(this).text('turn on the light')
            }else{
                $('body').css('backgroundColor','')
                $(this).text('Turn off the lights')
            }  
        } )
    </script>    
</body>
</html>

5. Case: interlaced discoloration

   <script src="jquery-1.12.4.js"></script>
    <script>
        $(function () {
            /*demand 
            1. Odd numbered lines are displayed in yellow and even numbered lines are displayed in green
            2. Move the mouse into each li element: the color turns red
            3. Move the mouse out of each li element to restore the original color
             */

            //1. The odd number line displays yellow (subscript is even), and the even number line displays green (subscript is odd)
            $('#ul1>li:even').css('backgroundColor', 'yellow');
            $('#ul1>li:odd').css('backgroundColor', 'green');

            //2. Move the mouse into each li element: the color turns red
            $('#ul1>li').mouseover(function () {
                //this: this is a DOM object. The currently clicked a tag does not support jquery syntax
                //$(this): This is the jquery object. The currently clicked a tag supports jquery syntax

                //(1). First, use the inline custom attribute to store the current color
                $(this).attr('bgc', $(this).css('backgroundColor'));
                //(2). Change the color to red
                $(this).css('backgroundColor', 'red');
            });

            //3. Move the mouse out of each li element to restore the original color
            $('#ul1>li').mouseout(function () {
                //Color restores the original color
                $(this).css('backgroundColor', $(this).attr('bgc'));
            });

        });
    </script>

6. Case: page skin change

<!DOCTYPE html>
<html>

<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        .small {
            width: 180px;
        }

        li {
            float: left;
            list-style: none;
            margin-right: 20px;
        }

        ul {
            width: 1000px;
            margin: 0 auto;

            height: 160px;

        }

        .father {
            width: 1000px;
            margin: 0 auto;
        }

        .father #bigPic {
            width: 1000px;
        }

        p {
            text-align: center;
        }
    </style>
</head>

<body>
    <ul id="ul1">
        <li><a href="https://picsum. photos/1000/622? Random = 1 "title =" beauty a "> < img
                    src="https://picsum.photos/180/112?random=1" alt="" class="small" /></a></li>
        <li><a href="https://picsum. photos/1000/622? Random = 2 "title =" beauty B "> < img
                    src="https://picsum.photos/180/112?random=2" alt="" class="small" /></a></li>
        <li><a href="https://picsum. photos/1000/622? Random = 3 "title =" beauty C "> < img
                    src="https://picsum.photos/180/112?random=3" alt="" class="small" /></a></li>
        <li><a href="https://picsum. photos/1000/622? Random = 4 "title =" beauty D "> < img
                    src="https://picsum.photos/180/112?random=4" alt="" class="small" /></a></li>
        <li><a href="https://picsum. photos/1000/622? Random = 5 "title =" beauty e "> < img
                    src="https://picsum.photos/180/112?random=5" alt="" class="small" /></a></li>
    </ul>
    <p>beauty A</p>
    <div class="father">
        <img src="https://picsum.photos/1000/622?random=1" alt="" id="bigPic" />
    </div>

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

    <script>
        // Click the a tag to prevent the default jump of the a tag
        // 1. Take out the href attribute of the a tag and assign it to the src of the bigPic tag



        // 2. Take out the text of the title attribute of the a tag and assign it to the text of the p tag
        $('a').on('click', function (e) {
            e.preventDefault()

            $('#bigPic').attr('src', $(this).attr('href'))

            $('p').text($(this).attr('title'))


        })


    </script>


</body>

</html>

7. Case: select all box button

<!DOCTYPE html>
<html>

<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        table {
            border-collapse: collapse;
            border: 1px solid #c0c0c0;
            width: 500px;
            margin: 100px auto;
            text-align: center;
        }

        th {
            background-color: #09c;
            font: bold 16px "Microsoft YaHei ";
            color: #fff;
            height: 24px;
        }

        td {
            border: 1px solid #d0d0d0;
            color: #404060;
            padding: 10px;
        }
    </style>
</head>

<body>
    <table>
        <tr>
            <th>
                <input type="checkbox" name="" id="checkAll" />Select all/None
            </th>
            <th>Dish name</th>
            <th>business</th>
            <th>Price</th>
        </tr>
        <tr>
            <td>
                <input type="checkbox" class="check" />
            </td>
            <td>braised pork in brown sauce</td>
            <td>Longjiang pig feet rice</td>
            <td>¥200</td>
        </tr>
        <tr>
            <td>
                <input type="checkbox" class="check" />
            </td>
            <td>Crispy ribs</td>
            <td>Longjiang pig feet rice</td>
            <td>¥998</td>
        </tr>
        <tr>
            <td>
                <input type="checkbox" class="check" />
            </td>
            <td>Beijing Roast Duck</td>
            <td>Longjiang pig feet rice</td>
            <td>¥88</td>
        </tr>
    </table>

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

    <script>
        /* 
            Form Boolean attribute: true/false
            $('Selector ') prop('attribute name ', attribute value)
            $('Selector ') prop('disabled')
            $('Selector ') prop('checked')
            $('Selector ') prop('selected')
        */

        //Click Select all
        $('#checkAll').on('click', function () {
            // $('.check').prop('checked', $('#checkAll').prop('checked'))
            // 1. Get the Boolean property of the all checkbox form
            console.log($('#checkAll').prop('checked'));//true/false
            // 2. Pass the Boolean attribute of the select all box to the radio box as the attribute value
            $('.check').prop('checked', $('#checkAll').prop('checked'))
        })

        // Click the radio box below
        $('.check').on('click', function () {
            /*       
                    //(1)Use the filter selector to get the number of all selected elements
                      let selNum = $('.check:checked').length
                      console.log(selNum);
                      //(2)Get the number of all check boxes 
                      let allNum = $('.check').length
                      //(3)Judge whether the checked elements are equal to the number of checked boxes
                      if (selNum == allNum) {
                          $('#checkAll').prop('checked', true)
                      } else {
                          $('#checkAll').prop('checked', false)
                      }
           */
            $('#checkAll').prop('checked', $('.check:checked').length == $('.check').length)

        })

    </script>

</body>

</html>

8. Extension: how can a constructor be called without new

 /* Principle: judge whether the user uses new. If not, use new to call recursively once*/
        function Zxk(name, age) {
            // new: direct assignment
            if (this instanceof Zxk) {
                this.name = name
                this.age = age
            } else {
                //No new: use new recursively to call yourself once
                return new Zxk(name, age)
            }
        }
        let p1 = new Zxk('ikun', 30)
        let p2 = Zxk('jx', 20)
        console.log(p1, p2);

Keywords: Javascript Front-end JQuery

Added by David Bethel on Sun, 02 Jan 2022 09:17:09 +0200