Knowledge supplement

Trigger Automatically triggers an event

Jq.trigger (‘click’)

< button > button < / button ><a href="javascript:;">link</a>
    
    <script>
        $('button').on('click'.function() {
            alert('Click the button');
        });

        $('a').on('click'.function(){
          // Clicking a triggers the button click event
          $('button').trigger('click');
        })
    </script>
Copy the code

1. The jQuery based

1.1 What is jQuery

Third party JS library (JS code file written by others, provided for everyone to use)

  • Function:
    • Go to the DOM tree to find the DOM element
    • Wrap an existing DOM/BOM object
    • The entry function
  • Jquery nature:
    • Is a wrapped method provided inside a JS file.
    • $is the alias of this jquery function!

1.1.1 JQ Object nature

  • Created by the jq function and returns: $(‘div’)
  • Is essentially a pseudo-array and provides a number of JQ methods

1.2 jQuery entry functions

  1. Instead of waiting for all the external resources to load, you can execute the internal code after the DOM structure has been rendered. JQuery wraps it for you.
  2. Equivalent to DOMContentLoaded in native JS.
// The first is easy to use. (recommended)
$(function () {...// This is the entry where the page DOM is loaded});// Second: cumbersome, but achievable
$(document).ready(function(){...// This is the entry where the page DOM is loaded
});

// Complement, equivalent to window.load
$(document).load(function(){...// This is the entry where the page DOM is loaded
});
Copy the code

1.3 The top-level object $in jQuery

  1. $is another name for jQuery. You can use jQuery instead in your code, but for convenience, you usually use $directly.
  2. $is jQuery’s top-level object, equivalent to the window in native JavaScript. You can call jQuery methods by wrapping elements with $as jQuery objects.

1.4 jQuery Objects and DOM Objects

  1. The object obtained with native JS is the DOM object
  2. The elements that the jQuery methods get are jQuery objects.
  3. The essence of jQuery object is to use $to wrap the DOM object into an object (stored as a pseudo-array).

Note:

Only jQuery objects can use jQuery methods; DOM objects use native JavaScirpt methods.

1.4 jQuery Object and DOM Object conversion

<script>
    let div = document.querySelector('div');
    // 1. Convert the DOM object into a jquery object
    let jDiv = $(div);
    jDiv.animate({
        left: 800
    }, 3000)


    // 2. Convert the jquery object into a DOM object
    let domDiv = jDiv[0];
    console.log(domDiv.tagName);
</script>
Copy the code

1.5 Obtain DOM objects and JQ objects by index number

let $divs = $('#content>div');
console.log($divs);
console.log($divs[0]);// Returns a DOM object
console.log($divs.eq(1));// Returns the encapsulated JQ object
Copy the code

2. JQuery selector

2.1 Basic selectors

Jq functions can look for don elements in the DOM based on CSS selectors

  • The jQ object (pseudo-array) is returned, which contains dom element objects found according to the selector and various JQ methods
$("Selector")   // Write CSS selectors to CSS selectors in quotes
Copy the code

2.2 Hierarchy selector

The two most commonly used hierarchical selectors are descendant selectors and child selectors.

    <script>
        $(function() {
            console.log($(".nav"));
            console.log($("ul li"));
        })
    </script>
Copy the code

2.3 Filter selectors

    <script>
        $(function() {$("ul li:first").css("color"."red");
            $("ul li:eq(2)").css("color"."blue");
            $("ol li:odd").css("color"."skyblue");
            $("ol li:even").css("color"."pink");
        })
    </script>
Copy the code

2.3.1 parents ()

The ability to look up all of the current parent elements (grandpa, etc.)

<div class="p-num">
    <div class="quantity-form">
        <a href="javascript:;" class="decrement">-</a>
        <input type="text" class="itxt" value="1">
    <a href="javascript:;" class="increment">+</a>
</div>

$('.increment').parents('.p-num')
Copy the code

2.3.1 Hidden cases are displayed in the drop-down list

    $(function() {
        let $li = $('.nav>li');
        // Add mouse-over events for all li tags in jq objects
        $li.mouseenter(function() {
            // This in the JQ event handler is also the event source DOM object
            // Encapsulate it as a JQ object to make it easier to call jQ methods
            let $this = $(this);
            // Get the child element ul of the current li
            $this.children('ul').show();
            // Get the child element a of the current li
            $this.children('a').css('backgroundColor'.'#eee');
        })

        $li.mouseleave(function() {
            let $this = $(this);
            $this.children('ul').hide();
            $this.children('a').css('backgroundColor'.' '); })})Copy the code

2.4 Implicit iteration

When we call jQ methods on JQ objects, the dom elements found in jQ objects are automatically iterated internally by those methods.

// The process of iterating through internal DOM elements (stored as pseudo-arrays) is called implicit iteration.
// Simple understanding: to match all elements loop through, execute the corresponding method, without us to loop again, simplify our operation, convenient for us to call.
$('div').hide();  // All divs in the page are hidden, no loop operation
Copy the code

The index method gets the subscript

2.4.1 setting styles in jQuery

// Change the inline style
$('div').css('properties'.'value')    
Copy the code

2.4.2 Exclusivity

// If you want to select one or more, the idea is exclusive: the current element is set in style, and the rest of the sibling elements are cleared.
$(this). The CSS (" color ", "red"); $(this). Siblings (). The CSS (" color ", "");Copy the code

2.4.3 Chain programming

The core principle: Most jQ object methods return a JQ object, so you can continue to call jQ object methods

// Chained programming is designed to save code and look more elegant.
$(this).css('color'.'red').sibling().css('color'.' '); 
Copy the code

3. Return values of different methods on the Jq object

  1. Return string
// Returns the SRC attribute of the image
jq.attr('src') 
Copy the code
  1. Returns a Boolean value
// Return whether the element contains the class name red (true/flase)
jq.hasClass('red')
Copy the code
  1. Returns the current JQ object
// Return the previous jq object
jq.css('color'.'red')
Copy the code
  1. Returns a new JQ object
// Return a new JQ object with sibling elements
jq.siblings()

$divs.eq(1)// Returns a new wrapped JQ object
$divs[0]// Returns a DOM object
Copy the code

3. Jquery-style operations

3.1 Operating the CSS

Note: With the CSS method, both get and modify areInline style.

// 1. The parameter is written only to the attribute name, which returns the attribute value
var strColor = $(this).css('color');

// 2. The parameters are the name of the attribute, the value of the attribute, separated by commas, and set a set of styles. The attribute must be quoted, and the value can not be quoted if it is a number
$(this).css(' 'color' '.' 'red' ');

// 3. Parameters can be in object form, which is convenient to set multiple groups of styles. Attribute names and attribute values are separated by colons, and attributes may not be quoted
//
$(this).css({ 
    "color":"white"."font-size":"20px"
});
// 3.1 Use the hump nomenclature for compound attributes; If it is not a number, it must be quoted; Numbers can be numbered without units. The default is PX
$(this).css({ 
    backgroundColor:"white",
    font-size:20.width:100.height:200
});
Copy the code

3.2 Setting class style methods

Notice the arguments in the action classDon't add

// 1. Add a class
$("div").addClass("current");

// 2. Delete the class
$("div").removeClass("current");

// 3. Switch classes
$("div").toggleClass("current");
Copy the code

In jQuery, class operations are performed only on the specified class, and do not affect the original className. It is equivalent to appending/removing/switching the specified className.

4. Effect of jQuery

  • Show hide: show()/hide()/toggle();

  • Draw: slideDown()/slideUp()/slideToggle();

  • FadeIn and out: fadeIn()/fadeOut()/fadeToggle()/fadeTo();

  • Custom animation: animate();

4.1 Display and Hide

4.4.1 show ()

4.1.2 hide ()

4.1.3 toggle ()

4.2 Slide in and slide out

Note:

  • Generally speaking, slideDown()– show, slideUp()– hide

  • If the position is bottom, slideDown() means hide and slideUp() means show

2 slideDown ()

4.2.2 slideUp ()

Holdings slideToggle ()

4.3 Fade in and out

4.3.1 fadeIn ()

4.3.2 fadeOut ()

4.3.3 fadeToggle ()

4.3.4 fadeTo() revises transparency

4.4 Custom Animation

4.4.1 the animate ()

<body>
    <button>move</button>
    <div></div>
    <script>
        $(function() {$("button").click(function() {$("div").animate({
                    left: 500.top: 300.opacity: 4..width: 500
                }, 500); })})</script>
</body>
Copy the code

4.5 Animate queues and stop queues

Animations or effects are executed once triggered, and if triggered more than once, multiple animations or effects are queued to execute.

To stop animation queuing: stop();

  • The stop() method is used to stop an animation or effect.
  • Stop () writes to the beginning of an animation or effect, stopping the previous animation.

Summary: Before each animation, call stop() before calling the animation.

$(".nav>li").hover(function() {
    // The stop method must be written before the animation
    $(this).children("ul").stop().slideToggle();
});
Copy the code

4.6 Accordion case

<script>
    $(function() {$('.king li').mouseenter(function() {
            // The current width of li is 224, the small image fades out, the large image fades in
            $(this).animate({
                width: 224
            }).find('.small').stop().fadeOut().siblings().stop().fadeIn();

            // Its sibling is 69 width, small image fades in, big image fades out
            $(this).siblings().animate({
                width: 69
            }).find('.small').stop().fadeIn().siblings().stop().fadeOut()
        })
    })
</script>
Copy the code

5. JQuery property operations

5.1 Inherent attribute value of elements prop()

An inherent attribute is an element’s own attribute, such as the href of the A element and the type of the input element.

Note the standard properties for manipulating elements. Prop properties are recommended!

// 1. Get the attribute element.prop(" Attribute name ") Get the inherent attribute values of the element
console.log($("a").prop("href"));
// 2. Set the properties
$("input").prop("checked".true);

console.log($("input").prop("checked"));// Select -true; Uncheck - false
console.log($("input").attr("checked"));// check -checked; Uncheck - undefined
Copy the code

5.1.1 Number of check boxes selected

// $('.j-checkbox:checked') checks that the selected small checkbox is a pseudo-array
    $('.j-checkbox').change(function() {
        // If the number of small check boxes is selected == Number of small check boxes, select all
        if ($('.j-checkbox:checked').length == $('.j-checkbox').length) {
            $('.checkall').prop('checked'.true);
        } else{$('.checkall').prop('checked'.false); }})Copy the code

5.2 Element Custom Attribute Value attr()

Attributes that the user adds to an element are called custom attributes. For example, add index = “1” to div.

Note: attr() is more suitable for handling custom properties than normal property operations. (This method can also get H5 custom attributes)

// 1. To get the element's custom attributes we call attr()
console.log($("div").attr("index"));
// 2. Set the element's custom attributes
$("div").attr("index".4);
Copy the code

5.3 Data Cache Data ()

The data() method accesses data on the specified element without modifying the DOM element structure. Once the page is refreshed, the previously stored data is removed.

Note: At the same time, you can also read the HTML5 custom attribute data-index, which is numeric.

// 3. Data cache () where data is stored in the element's memory
$("span").data("uname"."andy");
console.log($("span").data("uname"));
// This method gets the first data-index h5 custom attribute without writing data- and returns a number
console.log($("div").data("index"));
Copy the code

6. JQuery text attribute value

6.1 text Value of jQuery Content

There are three common operations: HTML ()/text()/val(); These correspond to the innerHTML, innerText, and value properties of the JS, which are specific to the content of the element and the value operation of the form.

<script>
  // 1. Get the content of the setting element HTML () -- equivalent to innerHTML
  console.log($("div").html());
  // $("div").html("123");
  
  // 2. Get the text content of the setting element text()-- equivalent to innerText
  console.log($("div").text());
  $("div").text("123");

  // 3. Get the Settings form value val()-- equivalent to value
  // Also use prop("value")
  console.log($("input").val());
  $("input").val("123");
</script>
Copy the code

7. JQuery element manipulation

7.1 Iterating over elements

JQuery implicit iteration does the same thing to the same type of element. If you want to do different operations on the same type of element, you need to use traversal.

Note: This method is used to iterate over each item in the jQuery object. The elements in the callback function are DOM objects.

7.1.1. The each ()

Iterate over the DOM elements inside the JQ object

// 1. each() iterates over elements
let sum=0;
let arr = ["red"."green"."blue"];
$("div").each(function(i, domEle) {
     // The first argument to the callback must be the index number
     // console.log(i);
     // The second argument to the callback must be a DOM element and the object is also self-named
     // console.log(domEle);
     // domEle.css("color"); Dom objects have no CSS methods
     $(domEle).css("color", arr[i]);
     sum += parseInt($(domEle).text());
})
Copy the code

7.1.2 $. The each ()

Alternative syntax for for loops /for etc

// the $.each() method iterates over elements
// 1. Iterate over the JQ object
$.each($("div"), function(i, ele) {
    console.log(i);
    console.log(ele);
});
// 2
$.each(arr, function(i, ele) {
     console.log(i);
     console.log(ele);
})

// 3. Iterate over the object
$.each({
            name: "andy".age: 18
}, function(i, ele) {
    console.log(i); // The output is the name of the name age attribute
    console.log(ele); // Outputs the value of the Andy 18 property


})
Copy the code

7.2 Creating, Adding, and Deleting a Vm

7.2.1 Creating an Element

    // 1. Create an element
    var li = $("
  • I was created later li
  • "
    ); Copy the code

    7.2.2 Adding elements

        // (1) Internal add
        $("ul").append(li);  // Add it internally and place it at the end of the content
        $("ul").prepend(li); // Add it internally and place it at the top of the content
        
        // (2) External add
        var div = $("
          
    I was born to my stepmother
    "
    ); // $(".test").after(div); $(".test").before(div); Copy the code

    7.2.3 Deleting Elements

        // 3. Delete elements
        // $("ul").remove(); // You can delete the matching element to commit suicide
        // $("ul").empty(); // Delete the child node of the matched element
        $("ul").html(""); // Delete the child node of the matched element
    Copy the code

    8. JQuery size and position operation

    8.1 jQuery Size Operations

    8.2 jQuery Position Operations

    Pay attention to

    • Offset can be taken as an offset or set (remember to clear all inner and outer margins first)
    • Position Obtains only the offset and cannot be set
    • Scroll is used to animate HTML and body elements, not documents, when you go back to the top$("body, html").stop().animate({scrollTop: 0});

    $(function() {
      // 1. Obtain the setting position (offset) offset from the document
      console.log($(".son").offset());
      console.log($(".son").offset().top);
      $(".son").offset({
          top: 200.left: 200
      });
      // 2. Obtain distance with parent position (offset) Position If there is no parent with parent position, the document prevails
      // This method can only get and not set offsets
      console.log($(".son").position());
      $(".son").position({
          top: 200.left: 200
      });// Cannot be set
    })
    Copy the code
    // 3. scroll
    $(function() {$(document).scrollTop(100);
        // scrollTop()/scrollLeft()
        // Page scroll events
        var boxTop = $(".container").offset().top;
        $(window).scroll(function() {
            if ($(document).scrollTop() >= boxTop) {
                $(".back").fadeIn();
            } else{$(".back").fadeOut(); }});// Return to the top
        $(".back").click(function() {
            // $(document).scrollTop(0);
            $("body, html").stop().animate({
                scrollTop: 0
            });
            
        // $(document).stop().animate({
        // scrollTop: 0
        / /}); Not the document, but the HTML and body elements})})Copy the code

    9. JQuery event handling

    9.1 Binding events on()

    $(function() {
        // 1. Single event registration
        $("div").click(function() {$(this).css("background"."purple");
        });
        $("div").mouseenter(function() {$(this).css("background"."skyblue");
        });
    
        // 2. Event processing on
        // (1) ON can bind one or more event handlers
        $("div").on({
            mouseenter: function() {$(this).css("background"."skyblue");
            },
            click: function() {$(this).css("background"."purple");
            },
            mouseleave: function() {$(this).css("background"."blue"); }}); $("div").on("mouseenter mouseleave".function() {$(this).toggleClass("current");
        });
        
        // (2) on implements event delegate (delegate)
        // $("ul li").click(); Click events bound to each li
        $("ul").on("click"."li".function() {
            alert(11);
        });
        // Click is bound to ul, but the trigger object is ul's li
        
        // (3) on can bind events to dynamically created elements in the future
        // $("ol li").click(function() {
        // alert(11);
        //}) cannot be directly bound to elements created in the future
        
        $("ol").on("click"."li".function() {
            alert(11);
        })
        var li = $("
  • I was created later
  • "
    ); $("ol").append(li); }) Copy the code

    9.2 OFF () Unbinding event

    $("div").on({
        click: function() {
            console.log("I clicked.");
        },
        mouseover: function() {
            console.log('I mouseover.'); }}); $("ul").on("click"."li".function() {
        alert(11);
    });
    // 1. Event unbind off
    $("div").off();  // This removes all events from the div
    $("div").off("click"); // This removes the click event from the div
    $("ul").off("click"."li");
    // 2.one () But it can only fire the event once
    $("p").one("click".function() {
        alert(11);
    })
    Copy the code

    9.3 Trigger () Automatically triggers an event

    $("div").on("click".function() {
        alert(11);
    });
    
    // Automatically triggers events
    // 1. Events ()
    $("div").click(); // Triggers the element's default behavior
    
    // 2. Element. Trigger (" event ")
    $("input").trigger("focus"); // Triggers the element's default behavior that the cursor flashes
    
    TriggerHandler (" event ") is the default behavior that does not fire elements
    $("input").on("focus".function() {$(this).val("How are you?");
    });
    $("input").triggerHandler("focus"); // The cursor does not blink
    Copy the code

    10. The jQuery object

    10.1 jQuery Event Object

    $(document).on("click".function() {
        console.log(I hit document); $(})"div").on("click".function(event) {
        console.log("I clicked div.");
        event.stopPropagation(); // Prevent upward bubbling
    })
    Copy the code

    10.2 jQuery Object Copy

    10.2.1 jq. Clone ()

    Deep copy

    10.2.2 $. The extend

    // $.extend(target, obj);
    // copy the contents of obj to target
    var targetObj = {};
    var obj = {
        id: 1.name: "andy"
    };
    $.extend(targetObj, obj); // obj = {id: 1; name: "andy"}
    
    var targetObj = {
        id: 0.msg: {
            sex: 'male'}};var obj = {
        id: 1.name: "andy".msg: {
            age: 18}}; $.extend(targetObj, obj);// Overwrite the original data in targetObj
    // 1. Shallow copy Copies the complex data type address of the original object to the target object, which will affect the obj object
    console.log(targetObj.msg.sex);// There is no such attribute
    
    // 2. Deep copy makes a full copy of the data inside the object to the target object. If there are non-conflicting attributes in the object, they will be merged together and will not affect the obj object
    $.extend(true, targetObj, obj);
    targetObj.msg.age = 20;
    console.log(targetObj);// MSG :{sex: "male ", age: 20}
    console.log(obj);// msg :{age: 18} 
    Copy the code

    10. The jQuery plugin

    JQuery plugins

    1. JQuery plugin library www.jq22.com/

    2. JQuery home of www.htmleaf.com/

      How to use jQuery plug-in

    3. Import relevant files. (jQuery file and plug-in file)

    4. Copy the relevant HTML, CSS, JS (call the plug-in).

    10.1 Waterfall Flow Plug-in (key)

    There are three uses of plug-ins:

    1. Introduce the CSS.
    2. The introduction of JS
    3. The introduction of HTML. (Some simple plug-ins only need to import HTML and JS, and some even need to import JS)

    10.2 Image lazy loading plug-in

    When the page slides to the position where there is an image, the image is loaded to improve the speed of page opening and user experience.

    1. The introduction of js
    // Must be written at the bottom of the body
    <script src="js/EasyLazyload.min.js"></script>
    <script>
       	lazyLoadInit({
       		showTime: 1100.onLoadBackEnd: function(i, e) {
         		console.log("onLoadBackEnd:" + i);
       		},
       		onLoadBackStart: function(i, e) {
         		console.log("onLoadBackStart:"+ i); }});</script>
    Copy the code
    1. The introduction of HTML
    // Replace all 
     <img data-lazy-src="upload/floor-1-3.png" alt="">
    Copy the code

    11. todolist

    Note: you must determine if! =null

    // Read the data stored locally
        function getData() {
            // Get the data
            let todoStr = localStorage.getItem('todo');
            // If there is data, it is converted to an array and returned
            // Note: we must check whether! =null cannot be written as '', because '' is a string, and null gets nothing
            if(todoStr ! =null) return JSON.parse(todoStr);
            // Otherwise, return null
            else return [];
        }
    Copy the code