jQuery quick start learning notes

0. Why learn jQuery?

  • jQuery is very useful! Get started quickly and operate DOM quickly!
  • If you are interested in some web scripts, jQuery is a good helper. Combined with the three swords, it can help you automatically complete the automatic questionnaire filling and some web page repeated operations
  • For web pages such as rotation map and waterfall navigation, templates can be directly introduced, which is still very friendly to newcomers
  • JQuery is extremely classic. It must have its excellence if it can live up to now. Don't exclude learning from jQuery. It's also excellent to know about ideas

1.jQuery

1.1 jQuery Download

  1. Open the official website

  1. Click to enter: ctrl+A select all, ctrl+c copy

  1. Create a new jQuery in vs Min.js file (any name here, as long as it is a JS file)
  2. Import in html file
<script src = "jquery.min.js"></script>

1.2 jQuery entry function

// The first method is recommended

$(function(){
    ...   // This is the entrance to the completion of page DOM loading 
})

// The second method
$(document).ready(function(){
    ... //This is the entrance to the completion of page DOM loading
})
  • After the DOM structure is rendered, the internal code can be executed. Instead of waiting until all external resources are loaded, jQuery helps us complete the encapsulation
  • Equivalent to DOMContentLoaded in native js
  • Unlike the load event in native js, the internal code is executed only after the page document, external js file, css file and picture are loaded
  • The first method is more recommended

1.3 top level object of jquery$

  1. $is a nickname of jQuery, which can be replaced by jQuery in code$
  2. $is the top-level object of jQuery, which is equivalent to window in native JavaScript.
  3. Wrap the element into a jQuery object with $, and you can call the method of jQuery.

1.4 jQuery object and DOM object

  1. DOM object: the object obtained with native js

  2. JQuery object: the object obtained by jQuery is a jQuery object.

    Essence: DOM elements are wrapped by $

  3. JQuery objects can only use jQuery methods, while DOM objects use native JavaScript properties and methods

1.5 jQuery object and DOM object conversion

  1. Convert DOM object to jQuery object:
$(DOM object)

$('div')

  1. Convert jQuery object to DOM object:
// The first method
$('div')[index]   index Is the index number


// The second method
$('div').get(index) index Is the index number

2.jQuery common API s

2.1 jQuery selector

2.1.1 jQuery basic selector

$("selector")   //Just write CSS selector directly inside, but use quotation marks

$(".nav");
$("ul li");
nameusagedescribe
ID Selector $("#id")Gets the element with the specified ID
Select all selector$('*')Match all elements
Class selector $(".class")Get elements of the same class
tag chooser $(".div")Get all elements of the same type of label
Union selector$("div,p,li")Select multiple elements
Intersection selector$("li.current")Intersection element

2.1.2 jQuery implicit iteration

The process of traversing internal DOM elements (stored in pseudo array form) is called implicit iteration

Simple understanding: loop through all the matched elements and execute the corresponding methods instead of us, which simplifies our operation and facilitates our call

2.1.3 jQuery filter selector

grammarusagedescribe
: first$('li:first')Get the first li element
: last$('li:last')Get the last li element
: eq(index)$("li:eq(2)")Among the obtained li elements, select the element with index number 2, and the index number starts from 0
: odd$("li:odd")Among the obtained li elements, select the element with odd index number
: even$("li:even")Among the obtained li elements, select the element with an even index number
// Select the first li in ul
$("ul li:first").css("color","red");

2.1.4 jQuery screening method (key)

grammarusageexplain
parent()$("li").parent();Find parent, the nearest parent element
children(selector)$("ul").children("li")Equivalent to $("UL > Li"), the nearest level (son)
find(selector)$("ul").find("li")Equivalent to $("ul li") descendant selector
siblings(selector)$(".first").siblings("li")Find sibling nodes, excluding itself
nextAll([expr])$(".first").nextAll()Find all peer elements after the current element
prevtAll([expr])$(".last").prevAll()Find all peer elements before the current element
hasClass(class)$('div').hasClass("protected")If there is a specific class, check whether there is a specific class
eq(index)$("li").eq(2);Equivalent to $("li:eq(2),index"), index starts from 0
$(function(){
    // 1. Parent
    $(".son").parent();
    
    // 2. Sub
    //(1) Son (children)  
    $(".nav").children("p");
    //(2) All children
    $(".nav").find("p");
    
    
    
    
    
    // 3. Brother
    //(1) siblings() all siblings except its own element
    $("ol .item").siblings("li");
    
    //(2) Nth eleme n t
    //(2.1) selection by means of selector
    $("ul li:eq(2)");
    //(2.2) use the selection method to select (recommended)
    $('ul li').eq(2);  
    
})

2.1.5 jQuery exclusivity

 $(function() {
            // Implicit iteration, binding click events to all buttons
            $("button").click(function() {
                // 2. The current element changes the background color
                $(this).css("background", "red");
                // 3. Other brothers remove the background color
                $(this).siblings("button").css("background", "")

            })
        })

2.1.6 jQuery chain programming

$(this).css("color","red").siblings().css("color","");

2.2 jQuery style operation

2.2.1 jQuery style css modification method

// 1. If the parameter only writes the property name, the property value is returned
$(this).css("color");

// 2. Parameters are attribute names and attribute values separated by commas. Set a set of styles. The attribute is quoted. The value is a number. Units and quotation marks are not allowed
$(this).css("color",300);

// 3. The parameter can be in the form of object, which is convenient for setting multiple groups of styles. Attribute names and attribute values are separated by colons, and attributes may not be quoted
$(this).css({
    "color":"red",
    "width": 400,
    "height": 400,
    backgroundColor: "red"
    // If it is a composite attribute, the hump naming method must be adopted. If the value is not a number, quotation marks are required
})

2.2.2 jQuery setting class style method

Be careful not to add points to the parameters in the operation class

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

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

// 3. Switching class
$("div").toggleClass("current");

2.2.3 differences between jQuery class operation and className

  • The className in the native JS will overwrite the original class name in the element
  • The class operation in jQuery only operates on the specified class and does not affect the original class name

2.3 jQuery effect

2.3.1 jQuery display and hiding effect

// Display syntax specification
show([speed,[easing],[fn]])       //Brackets indicate that all parameters can be omitted
$("div").show();
// Hide syntax specification
hide([speed,[easing],[fn]])
$("div").hide();
// Switch syntax specification
toggle([speed,[easing],[fn]])
$("div").toggle();

// 1. All parameters can be omitted and displayed directly without animation
// 2.speed: a string ("slow","normal",or "fast") representing one of the three predetermined speeds or a millisecond value representing the duration of the animation (e.g. 1000)
// 3. Eating: used to specify the switching effect. The default is "swing" (fast first and then slow). The parameter "liner" (uniform speed) can be used
// 4.fn: callback function, which is executed when the animation is completed. Each element is executed once

// 5. In general, no parameters are added and can be directly hidden!

2.3.2 jQuery sliding effect and event switching

// Sliding down
slideDown([speed,[easing],[fn]]) 
$("div").slideDown();

// Slide up
slideUp([speed,[easing],[fn]]) 
$("div").slideUp();

// Sliding switching effect
slideToggle([speed,[easing],[fn]]) 
$("div").slideToggle();

Event switching

hover([over,]out)

// Over: move the mouse over the element to trigger the function (equivalent to mouseenter)
// Out: the function to be triggered when the mouse moves out of the element (equivalent to mouseleave)



$("div").hover(function(){},function(){});
// The first function is the function passed by the mouse
// The second function is the function that the mouse leaves
// If hover only writes one function, this function will be triggered when the mouse passes and when the mouse leaves
$("div").hover(function(){
    $(this).slideToggle();
})

2.3.3 jQuery stop Animation

Once the animation or effect is triggered, it will be executed. If it is triggered multiple times, multiple animations or effects will be queued for execution

Stop queuing

stop()
// The stop() method is used to stop the animation or effect
// Note: stop() is written in front of the animation or effect, which is equivalent to stopping and ending the last animation

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

2.3.4 jQuery fade in, fade out and highlight effect

Fade in fade out

// Fade in
fadeIn([speed,[easing],[fn]])
$("div").fadeIn();
// Fade out
fadeOut([speed,[easing],[fn]])
$("div").fadeOut;
// Fade in and fade out switch
fadeToggle([speed,[easing],[fn]])

// All parameters can be omitted
// speed: a string ("slow","normal",or "fast") representing one of the three predetermined speeds or a millisecond value representing the duration of the animation (e.g. 1000)
// easing: used to switch effects. The default is "swing". The available parameter is "linear";
 
// Modify transparency. This speed and transparency must be written
fadeTo(speed,opacity,[easing],[fn])
$("div").fadeTo(1000,0.5)
// 1.opacity transparency must be written, and the value is between 0 and 1

2.3.5 jQuery custom animation method

animate(params,[speed],[easing],[fn])

// params: the style attribute you want to change is passed as an object and must be written. The attribute name can be without quotation marks. If it is a composite attribute, it needs to adopt hump naming method, such as borderLeft. Other parameters can be omitted



$("button").click(function(){
    $("div").animate({
        left: 500,
        top: 300,
        opacity: 0.4,
    },500)
})

2.4 jQuery attribute operation

2.4.1 obtaining intrinsic attribute values of elements

Inherent attribute: the attribute of the element itself

prop("attribute")

$("a").prop("href");

2.4.2 setting element intrinsic attribute value

prop("attribute","Attribute value")

$("a").prop("title","We're all fine~");

2.4.3 get element custom attribute value

attr("attribute")   // Similar to native getAttribute()

$("div").attr("index");

2.4.4 setting element custom attribute values

attr("attribute","Attribute value")  //setAttribute()

$("div").attr("index",4);

2.4.5 data cache ()

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

1. Additional data syntax

data("name","value")   //Attach data to the selected element

$("span").data("uname","andy");

2. Get data syntax

date("name")      //Get data from the selected element

$("span").data("uname");
// This method obtains the data index H5 custom attribute without writing data - the return is numeric (2)
$("div").data("index");

At the same time, you can also read the H5 custom attribute data index to get a numeric type

2.5 jQuery content text value

It mainly focuses on the content of elements and the value operation of forms

2.5.1 common element content (HTML)

Equivalent to native innerHTML

html()    // Gets the content of the element
$("div").html();

html("content") // Set the content of the element
$("div").html("123");

// Get the label of the tape < span > 123</span>

2.5.2 common element text content ()

Equivalent to native innerText

text()    //Gets the text content of the element
$("div").text();


text("Text content")  //Sets the text content of the element
$("div").text("123");
// 123  
// Obtained without label 123

2.5.3 get and set form value (VAL)

$("input").val();

$("input").val("Please enter the content~~~");

2.6 jQuery element operation

It is mainly used to traverse, create, add and delete elements

2.6.1 traversal elements

jQuery implicit iteration is to do the same operation on the same type of elements. If you want to do different operations on the same type of elements, you need to use traversal

// Grammar one
$("div").each(function(index,domEle){xxx;})

// The each() method iterates through each element that matches. It is mainly processed with DOM. Each
// The callback function inside has two parameters: index is the index number of each element; demEle is every DOM element, not a jQuery object
// Therefore, if you want to use the jQuery method, you need to convert this dom element into a jQuery object $(domelement)




// Grammar II

$.each(Object,function(index,element){xxx;})

// The $. each() method can be used to traverse any object, mainly for data processing, such as arrays and objects
// The function inside has two parameters: index is the index number of each element; Element traversal content
$.each(arr,function(index,element){
    console.log(index);
    console.log(element);
})


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

var arr = ["red","green","blue"];
$("div").each(function(index,domEle){
    $(domEle).css("color","arr[index]");
})

2.6.2 creating elements

$("<li></li>");
// Create a li tag dynamically
var li = $("<li>I was founded later li</li>");
var div =$("<div>I was later div</div>")

2.6.3 adding elements

// 1. Internal addition
element.append("content")
$("ul").append(li);
// Added internally and placed at the end of the content, similar to the native appendChild

element.prepend("content")
$("ul").prepend(li);
// Added internally and placed at the top of the content,



// 2. External addition
element.after("content");
$(".test").after(div);
// Put the content after the target element

element.before("content");
// Put the content in front of the target element

1. Add elements internally. After generation, they are parent-child relationships

2. Add external elements. After generation, they are brothers

2.6.4 deleting elements

1.element.remove()      //Delete the matching element (itself)
$("ul").remove();

2.element.empty()       //Delete child nodes (children) in matching elements
$("ul").empty();

3.element.html("")      //Delete child nodes (children) in matching elements

2.7 jQuery dimensions

grammarusage
width() / height()Get the width and height of the matching element, and only calculate the width / height
innerWidth() / innerHeight()Get the width and height of the matching element, including padding
outerWidth() / outerHeight()Get the width and height values of matching elements, including padding and border
outerWidth(true) / outerHeight(true)Get the width and height values of matching elements, including padding, border and margin

1. If the above parameter is empty, the corresponding value is obtained and the returned value is numeric

2. If the parameter is numeric, modify the corresponding value

3. The parameter does not need to be written in unit

$("div").width(); 
// Gets or sets the element width and height sizes

$("div").innerWidth();
// Gets or sets the element width and height + padding size


$("div").outerWidth();
//Gets or sets the width and height + padding +border sizes

$("div").outerWidth(true);
//Gets or sets the width and height + padding +border + margin sizes

2.8 jQuery location

2.8.1 offset() sets or gets the element offset

1. The offset () method sets or returns the offset coordinates of the selected element relative to the document, which has nothing to do with the parent

$(".son").offset();
$(".son").offset().top;

$(".son").offset({
    top: 200,
    left: 200
});



// This method has two attributes: left and top offset(). Top is used to obtain the distance from the top of the document, offset() Left is used to get the distance to the left of the document
// You can set the offset of the element: offset({top: 10,left: 30});

2.8.2 position() get element offset

1. The position () method is used to return the offset coordinates of the selected element relative to the parent with positioning. If the parent has no positioning, the document shall prevail

$(".son").position();

// This method can only get the offset and cannot set the offset

2.8.3 scrollTop() / scrollLeft() sets or gets the header and left side of the rolled element

// Page scroll event
$(window).scroll(function(){
    $(document).scrollTop();
})

3.jQuery event

3.1 jQuery event registration

3.1.1 single event registration

element.event(function(){})

$("div").click(function(){})

3.2 jQuery event handling

3.2.1 event handling on() binding event

// The on() method binds the event handler of one or more events on the matching element
element.on(events,[selector],fn)

// events: one or more event types separated by spaces, such as "click" or "keydown"
// Selector: the child element selector of the element
// fn: callback function


$("div").on({
    mouseenter: function(){
        $(this).css("background","skyblue");
    },
    click: function(){
        $(this).css("background","purple");
    }
})

  • on() method advantage 2:

You can delegate actions to events The definition of event delegation is to bind the event originally added to the child element to the parent element, that is, to delegate the event to the parent element

$("ul").on("click","li",function(){
    alert("hello world!");
});

//The event is bound to the ul. Only one ul adds a click event, but the trigger object is li. The event bubble will occur. When it bubbles to the father, the father will execute this function
  • on() method advantage 3:

For dynamically created elements, click() cannot bind events. on() can bind events to dynamically generated elements in the future

// traditional method 
$("ol li").click(function(){
    alert(11);
})
var li = $("<li>I was founded later</li>")
$("ol").append(li);
// It's useless. Dynamically created elements can't bind events


// on can bind events to dynamically created elements in the future
$("ol").on("click","li",function(){
    alert(11);
})
var li = $("<li>I was founded later</li>")
$("ol").append(li);

3.2.2 event handling (off) unbinding event

  • The off() method removes the event handler added through the on() method.
$("div").off(); // This is to take all the events except div
$("div").off("click");  //This is to release the click event on the div
$("ul").off("click","li"); //This is the unbinding event delegate
  • If you want to execute some events only once and don't execute them any more, you can use the one() method
$("p").one("click",function(){
    alert(11);
})

3.3.3 jQuery auto trigger event

// 1. Elements Event ()
$("div").click();

// 2. Elements trigger("event")
$("div").trigger("click");

// 3. Elements The trigger handler ("event") does not trigger the default behavior of the element
$("div").triggerHandler("click");

3.3 jQuery event object

When the event is triggered, the event object will be generated

element.on(events,[selector],function(event){})

// Block default behavior: event Preventdefault() or return false
// Prevent bubbling: event stopPropagation()


$(function(){
    $(document).on("click",function(){
        console.log("Click document");
    })
    $("div").on("click",function(event){
        console.log("Click div");
        event.stopPropagation();
    })
})

Keywords: Javascript JQuery

Added by sitorush on Thu, 03 Feb 2022 05:19:28 +0200