This is the twelfth day of my participation in Gwen Challenge

1.1 at the beginning of knowledge

1.1.1 Entry function

The function is equivalent to the onload event, which can be executed after the DOM structure is rendered

But it’s different

The onload event does not execute the internal code until the page documents, external JS files, CSS files, and images have been loaded.

/ / the first
$(function () {.../ / content});/ / the second
$(document).ready(function(){.../ / content
});
Copy the code

1.1.2 Top-level object $

You can use jQuery instead, which is equivalent to the window in native JS

1.1.3 jQuery Objects and DOM Objects

  1. The objects obtained with native JS are DOM objects
  2. The elements that the jQuery methods get are jQuery objects.
  3. JQuery objects are wrapped DOM objects (stored as pseudo-arrays)

JQuery objects can only use jQuery methods

1.1.4 jQuery Object and Dom Object Conversion

// DOM objects are converted to jQuery objects
var box = document.getElementById('box');  // Get the DOM object
var jQueryObject = $(box);  // Convert DOM objects to jQuery objects

// There are two ways to convert jQuery objects into DOM objects:
// jQuery object [index]
var domObject1 = $('div') [0]
// get(index)
var domObject2 = $('div').get(0)
Copy the code

2.1 jQuery selector

2.1.1 Basic selectors

The name of the usage describe
The ID selector $(‘#id’) Gets the element with the specified ID
Full selection selector $(‘ * ‘) Match all elements
Class selectors $(“.class”) Gets elements of the same class
Label selector $(“div”) Gets all elements of the same class of tags
Union selector $(“div,p,li”) Select multiple elements
Intersection selector $s(“Ii.current”) Intersection elements

2.1.2 Hierarchical selectors

The name of the usage describe
Child selector $(“ul>li”); Use the > sign to get the parent son level element; Note that grandchild level elements are not retrieved
Descendant selector $(“ul li”); Get all li elements under UL, including grandchildren, using Spaces to represent descendant selectors

2.1.3 Filtering selectors

The name of the usage describe
:first $(‘li:first’) Gets the first Li element
:last $(‘li:last’) Gets the last Li element
:eq(index) $(“li:eq(2)”) From the obtained li element, select the element with index number 2, starting with index number 0.
:odd $(“li:odd”) Select the element whose index number is odd from the obtained li element
:even $(“li:even”) From the li element, select the element whose index number is even

2.1.4 Other selectors

grammar usage instructions
parent() $(“li”).parent(); Look for the parent
children(selector) $(“ul”).children(“”li”) Equivalent to $(“ul> Li “), nearest grade (biological son)
find(selector) $(“ul”).find(“li”); Equivalent to $(“ul Li “), descendant selector
siblings(selector) $( “.first”).siblings(“li”); Find sibling nodes, not including itself
nextAll([expr]) $(“.first”).nextAll() Find all the peers after the current element
prevtAll([expr]) $(“.last”). prevAll() Finds all the peers of the current element
hasclass(class) $( ‘div ‘ ).hasClass(“protected”) Checks if the current element contains a particular class and returns true if it does
eq(index) $(“li”).eq(2); Equivalent to $(“li:eq(2)”),index starts at 0

2.2 Basic Knowledge

2.2.1 Exclusivity

$(this). The CSS (" color ", "red");// Change your color
$(this). Siblings (). The CSS (" color ", "");// Brother color removal
Copy the code

2.2.2 Implicit Iteration

The process of iterating through DOM objects in jQuery is called implicit iteration

$('div').hide(); // All divs in the page are hidden
Copy the code

2.2.3 Chain programming

$(this).css('color'.'red').sibling().css('color'.' '); 
Copy the code

3.1 Style Operation

3.1.1 operating CSS

var strColor = $(this).css('color');

$(this).css(' 'color' '.' 'red' ');

// Parameters can be in the form of objects, which makes it easy to set multiple styles. Attribute names and attribute values are separated by colons, and attributes may not be quoted
$(this).css({ "color":"white"."font-size":"20px"});
Copy the code

In general, you add styles by writing them in style and by adding classes

3.1.2 Method of setting the class Name

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

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

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

ClassName overrides the className in native js. In jQuery, the className is specified without affecting the original className

3.2 effect of jQuery

Note:

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

Stop animation queuing: stop();

This will stop the animation while it is executing

3.2.1 Display and Hide

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

About the parameters

Parameters can be omitted, no animation directly displayed

The first parameter speed: three predetermined speeds (show, normal, fast) or the number of milliseconds in which the animation takes place

The second argument easing: Specifies the switching effect. It defaults to ‘swing’ and can also be set to ‘Linear’

The third argument fn: the callback function, which is executed when the animation completes

3.2.2 Slide in and slide out

  • Slide in and slide out: slideDown()/slideUp()/slideToggle();

3.2.3 Fade in and out

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

FadeTo () must say speed and transparency, which indicates the maximum transparency after fading

<script>
    $(function() {$('button').eq(0).click(function() {$('div').stop().fadeIn(); $(})'button').eq(1).click(function() {$('div').stop().fadeOut(); $(})'button').eq(2).click(function() {$('div').stop().fadeToggle(); $(})'button').eq(3).click(function() {$('div').stop().fadeTo(100.3.);
        })
    })
</script>
Copy the code

3.2.4 Custom Animation

  • Custom animation: animate();

The first parameter is passed in the changed style property as an object. Note that the compound property is named with a hump. The last three parameters can be omitted

<script>
    $(function() {$('button').click(function() {$('div').animate({
                left: 500.top: 300.opacity: . 5.hight: 300
            })
        })
    })
</script>
Copy the code

Note that div must be positioned when setting top and left, otherwise it will not work

3.2.5 Event Switchover

JQuery has the hover() event, which functions like the HOVER in CSS

hover(function.function)
Copy the code

Pass in two arguments. The first argument is the function that fires when the mouse moves in and the second argument is the function that fires when the mouse moves out

It is triggered when the mouse moves in and out of a single argument

4.1 jQuery Property Operations

4.1.1 Inherent attribute value of elements prop()

Get the attributes of the element itself to facilitate manipulation of the form

  • Form attributes:disabled checkedThis kind of property manipulation is smooth
/ / to get
prop('Attribute name');

/ / change
prop('Attribute name'.'Attribute value');
Copy the code

4.1.2 Element Custom Attribute Value attr()

/ / to get
attr('Attribute name');

/ / change
attr('Attribute name'.'Attribute value');
Copy the code

4.1.3 Data Cache Data ()

You can access data on the specified element without modifying the DOM element structure. Page refresh cache cleared

data('myName'.'ljc');// Add data to the element

data('myName');// Read data to the element
Copy the code

4.1.4 All Button

The: Checked selector returns the selected element as an array

$(function() {$('.all').change(function() {$('.child').prop('checked', $('.all').prop('checked'));// Select all button$(})'.child').change(function() {
        if($('.child:checked').length == $('.child').length) {
            $('.all').prop('checked'.true);// If all the small buttons are selected, check them all
        }else{$('.all').prop('checked'.false); }})})Copy the code

4.2 Text Attributes

4.2.1 Text content

  • Common element content

The ones you get are tagged

You can change the content by passing in parameters

<div>
    <span>123</span>
</div>

<script>
    console.log($('div').html());// <span>123</span>
    $('div').html('ljc'); // only LJC is left in div
</script>
Copy the code
  • Plain element text content

Only the content of the text is retrieved, not the label

  • The form value val()
console.log($("input").val());// Get the contents of the form
$("input").val("123");// Change the form content
Copy the code

Keep 2 decimal places toFixed(2)

4.3 Element Operations

4.3.1 Iterating over elements

Implicit iteration is doing the same thing for the same type of element, but still using traversal to do different things

$('div').each(function(index, domEle) {});
Copy the code
  • Is a DOM object, not a jQuery object, and needs to be converted to a jQuery object to use a method
$.each(obj,function(index,domele){})
Copy the code

Can be used to walk through any object, mainly for data processing,

var sum = 0;
var arr = ['red'.'blue'.'yellow'];
$('div').each(function(index, domEle) {
    //index is the index number. DomEle is the DOM element object
    $(domEle).css('color', arr[index]);
    // Convert to an integer, otherwise print 0123, concatenated as a string
    sum += parseInt($(domEle).text());
})
console.log(sum);/ / 6

$.each({
    name: 'ljc'.age: 20
},function(i,ele) {
    console.log(i); // name age
    console.log(ele); // 'ljc' 20
})
Copy the code

4.3.2 Manipulating elements

  • Create the element
var li = $('
  • Newly created element
  • '
    ); Copy the code
    • ** Adds elements (** adds later)
    $('ul').append(li);
    Copy the code
    • Add elements (before)
    $('ul').prepend(li);
    Copy the code
    • External add (added before)
     $('div').before(div);
    Copy the code
    • External add (add later)
     $('div').after(div);
    Copy the code
    • Remove elements
    $('ul').remove();// Delete the entire ul
    Copy the code
    • Removes child nodes from a collection of elements
    $('ul').empty();// Delete the contents of ul
    Copy the code
    • Clear it in HTML
    $('ul').html();
    Copy the code

    4.4 Operation of size and position

    4.4.1 jQuery Size Operation

    grammar usage
    width() / height() Get the matching element width and height values only including width/height
    innerWidth() /innerHeight() Gets the width and height of the matching element including the padding
    outerWidth() / outerHeight() Get matching element width and height values including padding and border
    outerWidth(true) / outerHeight(true) Get the width and height values of the matching elements including padding, border, and margin
    • The return value is numeric
    • If the argument is numeric, modify the style
    • Parameters are not written in units

    4.4.2 jQuery Position Operations

    1. offset()Sets the offset of the fetch element

    The position obtained is the offset coordinate relative to the document and has no relation to the parent

    The argument passed in is an object

    // Get the offset
    $('div').offset()
    // Change the location
    $('div').offset({
          top: 200.left: 100
    })
    Copy the code
    1. position()Gets an offset with a location

    The position obtained is relative to the parent element with positioning

    This method can only be obtained, not modified

    $('div').position()
    Copy the code
    1. scrollTop() scrollLeftSets the head and left side of the element to be rolled away

    No follow argument is get, follow argument is set

    5.1 the jQuery event

    5.1.1 Bind events on()

    Benefits of binding events to on()

    1. You can bind multiple events, multiple event handling functions
    $('div').on({
        mouseover : function() {},
        click : function() {}}) $('div').on('mouseenter mouseleave'.function() {$(this).toggleClass('currrnt');
    })// This method can be used if the same programs are executed
    Copy the code
    1. Event delegation
    $('ul').on('click'.'li'.function() {
           alert('hello world');
     })
    Copy the code
    1. For newly created elements,clickUnable to bind, butoncan
    $('div').on('click'.'p'.function() {
        alert('Don't light on me.'); $(})'div').append($('

    New

    '
    )) Copy the code

    5.1.2 OFF () Unbind event

    • Remove all events
    $('div').off()
    Copy the code
    • Release specific event
    $('div').off('click')
    Copy the code
    • Disengagement of event delegation
    $('div').off('click','li')
    Copy the code
    • An event that fires only once
    $('div').one('click'.function(){})
    Copy the code

    5.1.3 Tigger () automatically triggers an event

    // Triggers the element's default behavior
    $("div").click();
    // Triggers the element's default behavior
    $("div").trigger("click");
    // Does not trigger default behaviors, such as automatically getting focus
    $("input").triggerHandler("focus");// Does not get focus
    Copy the code

    6.1 jQuery Event Objects

    Basically the same event object as native JS

    PreventDefault behavior: event.preventdefault (),return false

    Stop bubbling: event.stopPropagation()

    6.1.1 Copying Objects

    $.extend([deep], target, obj1)

    1. [deep] : true for deep copy, false by default for shallow copy
    2. Target Indicates the object to be copied
    3. Obj Specifies the object to be copied
    $(function() {
        var targetObj = {
            sex : 'male'
        };
        var obj = {
            id: 1.name: 'andy'
        };
        $.extend(targetObj,obj);// v copies obj to targetObj
        console.log(targetObj);// {sex: "male", id: 1, name: "andy"}
        console.log(obj); // {id: 1, name: "andy"}
    })
    Copy the code

    If more than one object is passed in, the next object overwrites the previous one

    6.1.2 Coexistence of multiple libraries

    Used to resolve naming conflicts

    JQuery solution

    1. Replace $with jQuery.jQuery('div')
    2. Custom name. var xx = $.noConflict();
    <script>
    	$(function() {
      		// let jquery release control over $
      		var ljc = jQuery.noConflict();
      		console.log(ljc("span"));
    	})
    </script>
    Copy the code

    7.1 the jQuery plugin

    1. Introduce the CSS.
    2. The introduction of JS
    3. The introduction of HTML.