Common jQuery API s: jQuery selector, jQuery style operation, jQuery effect, jQuery property operation, text property value, jQuery element operation, jQuery size, position operation

Keywords: JQuery

1. jQuery selector

1.1 jQuery Basic Selector

Native JS fetches elements in a variety of ways, is complex, and has inconsistent compatibility, so jQuery encapsulates us to achieve a uniform standard for fetching elements.

$("selector") // Inside selector Write CSS selector directly, but quote
Nameusagedescribe
Select all selectors$("*")Match all elements
tag chooser$("div")Get all elements of the same type of label
Class selector$(".class")Get all elements of the same type of label
ID Selector$("#id")Gets the element of the specified ID
Union selector$("div,p,li")Select multiple elements
Intersection selector$("li.current")Intersection Elements

1.2 jQuery Hierarchy Selector

Nameusagedescribe
Descendant selector$("ul > li")Use the > sign to get elements at the parent-son level; note that elements at the grandchild level are not taken
Descendant Selectors$("ul li")Use spaces to represent descendant selectors, get all li elements under ul, including grandchildren, etc.

jQuery Setting Style

$('div').css('attribute', 'value')

1.3 Implicit Iteration (Important)

The process of traversing internal DOM elements (stored as pseudo arrays) is called implicit iteration.

Simple understanding: Loop through all the elements that match, and execute the corresponding methods, without us looping again, to simplify our operation and make it easier for us to invoke.

1.4 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)")Of the li elements you get, select the one with index number 2, and index number index starts with 0
:odd$("li:odd")Select the element whose index number is odd among the li elements you get
:even$("li:even")Select the element whose index number is even among the li elements you get

1.5 jQuery Filtering Method (Key)

grammarusageExplain
parent()$("li").parent()Find Parent
children(selector)$("ul").children("li")Equivalent to $("ul > li"), last level (parent-son)
find(selector)$("ul").find("li")Equivalent to $("ul li"), descendant selector
siblings(selector)$(".first").siblings("li")Find sibling nodes, not including yourself
nextAll([expr])$(".first").nextAll()Find all peer elements after the current element
prevAll([expr])$(".last").prevAll()Find all peer elements before the current element
hasClass(class)$("div").hasClass("protected")Checks if the current element contains a specific class and returns true if it does
eq(index)$("li").eq(2)Equivalent to $("li:eq(2)"), index starts at 0

Keep in mind: parent(), children(), find(), siblings(), eq()

Exclusive Ideas in 1.6 jQuery

To choose more than one effect, think exclusively: the current element sets the style, the rest of the sibling elements clear the style.

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

1.7 Chain Programming

Chain programming is designed to save code and look elegant.

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

2. jQuery style operations

2.1 Operation css method

jQuery can use the css method to modify simple element styles; it can also manipulate classes to modify multiple styles.

(1) A parameter that only writes the attribute name returns the attribute value.

$(this).css("color");

(2) Parameters are attribute names, attribute values, comma-separated, set a set of styles, attributes must be quoted, values may not follow units and quotes if they are numbers.

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

(3) Parameters can be in the form of objects to facilitate multiple sets of styles. Attribute names and values are separated by colons, and attributes can be unquoted.

$(this).css({ "color":"white","font-size":"20px"});

2.2 Setting Class Style Methods

Equivalent to the previous classList, you can manipulate class styles, taking care that the parameters inside the operation class are not dotted.

(1) Add classes

$("div").addClass("current");

(2) Remove classes

$("div").removeClass("current");

(3) Switching classes

$("div").toggleClass("current");

Class 2.3 operations differ from className

  • className in native JS overrides the class name inside the element.
  • Class operations in jQuery only operate on the specified class, without affecting the original class name.

3. jQuery Effect

jQuery packages a lot of animation effects for us, most commonly as follows:

3.1 Show Hidden Effects

(1) Display grammar specification

show([speed,[easing],[fn]])

(2) Hide grammar specifications

hide([speed,[easing],[fn]])

(3) Switching grammar specifications

toggle([speed,[easing],[fn]])

(4) Show, hide, switch parameters

  • Parameters can be omitted and displayed directly without animation.
  • speed: A string ("slow", "normal", "or"fast") representing one of the three preset speeds or a millisecond value representing the length of the animation (for example, 1000).
  • easing:(Optional) is used to specify the switching effect, defaulting to "swing", with the parameter "linear".
  • fn: Callback function, which is executed once per element when the animation is complete.

Suggestion: Usually no parameters, just show hide directly.

Example:

<body>
    <button>display</button>
    <button>hide</button>
    <button>switch</button>
    <div></div>
    <script>
        $(function() {
            $("button").eq(0).click(function() {
                $("div").show(1000, function() {
                    alert(1);
                });
            })
            $("button").eq(1).click(function() {
                $("div").hide(1000, function() {
                    alert(1);
                });
            })
            $("button").eq(2).click(function() {
              $("div").toggle(1000);
            })
            // Normally, we just show hiding without parameters
        });
    </script>
</body>

3.2 Sliding effect

(1) Syntax Specification for Sliding Effects

slideDown([speed,[easing],[fn]])

(2) Syntax Specification for Sliding Effects

slideUp([speed,[easing],[fn]])

(3) Syntax Specification for Sliding Switching Effect

slideToggle([speed,[easing],[fn]])

(4) Sliding effect, sliding up effect, sliding switch parameters

  • Parameters can be omitted.
  • speed: A string ("slow", "normal", "or"fast") representing one of the three preset speeds or a millisecond value representing the length of the animation (for example, 1000).
  • easing:(Optional) is used to specify the switching effect, defaulting to "swing", with the parameter "linear".
  • fn: Callback function, which is executed once per element when the animation is complete.

Example:

<body>
    <button>Drop Slide</button>
    <button>Slide up</button>
    <button>Toggle Slide</button>
    <div></div>
    <script>
        $(function() {
            $("button").eq(0).click(function() {
                // Slide down slideDown()
                $("div").slideDown();
            })
            $("button").eq(1).click(function() {
                // Slide slideUp()
                $("div").slideUp(500);
            })
            $("button").eq(2).click(function() {
                // Slide Toggle ()
                $("div").slideToggle(500);
            });
        });
    </script>
</body>

3.3 Event Switching

hover([over,]out)

(1) over: Mouse over the element to trigger the function (equivalent to mouseenter).

(2) out: The function (equivalent to mouseleave) that the mouse moves out of an element to trigger.

(3) If only one function is written, it will be triggered when the mouse passes and leaves.

3.4 Animation Queue and Stop Queuing Method

(1) Animation or effect queue

Animations or effects are executed once triggered, and if triggered multiple times, multiple animations or effects are queued for execution.

(2) Stop queuing

stop()
  • The stop() method is used to stop an animation or effect.
  • Note: stop() writing in front of an animation or effect is equivalent to stopping the last animation.

Example:

<body>
    <ul class="nav">
        <li>
            <a href="#">Weibo</a>
            <ul><li><a href="">Private letter</a></li><li><a href="">comment</a></li><li><a href="">@I</a></li></ul>
        </li>
        <li>
            <a href="#">Weibo</a>
            <ul><li><a href="">Private letter</a></li><li><a href="">comment</a></li><li><a href="">@I</a></li></ul>
        </li>
    </ul>
    <script>
        $(function() {
            // Mouse Passes
            // $(".nav>li").mouseover(function() {
            //     // $(this) jQuery current element this does not quote
            //     // show() Shows hidden elements hide()
            //     $(this).children("ul").slideDown(200);
            // });
            // //Mouse away
            // $(".nav>li").mouseout(function() {
            //     $(this).children("ul").slideUp(200);
            // });
            // 1.Event switching hover is a compound way of writing mouse over and off
            // $(".nav>li").hover(function() {
            //     $(this).children("ul").slideDown(200);
            // }, function() {
            //     $(this).children("ul").slideUp(200);
            // });
            // 2.Event switching hover If only one function is written, then mouse passing and mouse leaving trigger this function
            $(".nav>li").hover(function() {
                // The stop method must be written before the animation
                $(this).children("ul").stop().slideToggle();
            });
        })
    </script>
</body>

3.5 Fade effect

(1) Fade-in effect grammar specification

fadeIn([speed,[easing],[fn]])

(2) Fade-out effect grammar specification

fadeOut([speed,[easing],[fn]])

(3) Grammatical specification for fade-in and fade-out switching effects

fadeToggle([speed,[easing],[fn]])

(4) Fade-in effect, fade-out effect, fade-in and fade-out switch effect parameters

  • Parameters can be omitted and displayed directly without animation.
  • speed: A string ("slow", "normal", "or"fast") representing one of the three preset speeds or a millisecond value representing the length of the animation (for example, 1000).
  • easing:(Optional) is used to specify the switching effect, defaulting to "swing", with the parameter "linear".
  • fn: Callback function, which is executed once per element when the animation is complete.

(5) Gradually adjust to specified opacity

fadeTo([[speed],opacity,[easing],[fn]])

Parameters:

  • opacity transparency must be written between 0 and 1.
  • speed: A string ("slow", "normal", "or"fast") representing one of the three preset speeds or a millisecond value representing the length of the animation (for example, 1000). Must be written.
  • easing:(Optional) is used to specify the switching effect, defaulting to "swing", with the parameter "linear".
  • fn: Callback function, which is executed once per element when the animation is complete.

Example:

<body>
    <button>fadein</button>
    <button>Fade out effect</button>
    <button>Fade in and out switch</button>
    <button>Modify Transparency</button>
    <div></div>
    <script>
        $(function() {
            $("button").eq(0).click(function() {
                // fadeIn()
                $("div").fadeIn(1000);
            })
            $("button").eq(1).click(function() {
                // fadeOut()
                $("div").fadeOut(1000);
            })
            $("button").eq(2).click(function() {
                // Fade in and fade out toggle ()
                $("div").fadeToggle(1000);
            });
            $("button").eq(3).click(function() {
                //  Modify transparency fadeTo() This speed and transparency must be written
                $("div").fadeTo(1000, 0.5);
            });
        });
    </script>
</body>

3.6 Custom animate

(1) Grammar

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

(2) Parameters

  • params: Style attributes that you want to change must be written to be passed as objects. Attribute names can be unquoted, and camel naming borderLeft is required for composite attributes. The rest of the parameters can be omitted.
  • speed: A string ("slow", "normal", "or"fast") representing one of the three preset speeds or a millisecond value representing the length of the animation (for example, 1000).
  • easing:(Optional) is used to specify the switching effect, defaulting to "swing", with the parameter "linear".
  • fn: Callback function, which is executed once per element when the animation is complete.

Example:

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

4. jQuery attribute operation

4.1 Set or get the element's intrinsic attribute value prop()

The so-called intrinsic attribute of an element is its own attribute, such as the href inside the element, such as the type inside the element.

(1) Get Attribute Grammar

prop("attribute")

(2) Setting attribute grammar

prop("attribute", "Attribute Value")

Note: prop() is more suitable for manipulating form attributes than normal attribute operations: disabled / checked / selected, etc.

4.2 Set or get element custom attribute value attr()

Users add their own attributes to elements, which we call custom attributes. For example, add an index = "1" to a div.

(1) Get Attribute Grammar

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

(2) Setting attribute grammar

attr("attribute", "Attribute Value") // Similar to native setAttribute()

Note: attr() is more suitable for manipulating custom attributes than for normal attribute operations. (This method also obtains H5 custom attributes.)

4.3 Data cache data()

The data() method accesses data on specified elements without modifying the DOM element structure. Once the page refreshes, the previously stored data will be removed.

(1) Additional data syntax

data("name", "value") // Attach data to selected elements

(2) Grammar for obtaining data

date("name") // Get data from selected elements

Note: You can also read the HTML5 custom attribute data-index to get a numeric type.

<body>
    <a href="http://Www.itcast.cn "title=" is good "> are good </a>
    <input type="checkbox" name="" id="" checked>
    <div index="1" data-index="2">I am div</div>
    <span>123</span>
    <script>
        $(function() {
            //1. element.prop("attribute name") Gets the intrinsic attribute value of an element
            console.log($("a").prop("href"));
            $("a").prop("title", "We're all fine");
            $("input").change(function() {
                console.log($(this).prop("checked"));
            });
            // console.log($("div").prop("index"));
            // 2. Element's custom attributes We pass attr()
            console.log($("div").attr("index"));
            $("div").attr("index", 4);
            console.log($("div").attr("data-index"));
            // 3. Data Cache data() This data is stored in the element's memory
            $("span").data("uname", "andy");
            console.log($("span").data("uname"));
            // This method gets the data-index h5 custom property The first one does not write data-and returns a numeric type
            console.log($("div").data("index"));
        })
    </script>
</body>

5. jQuery Text Attribute Value

There are three common operations: html() / text() / val(); they correspond to innerHTML, innerText, and value attributes in JS, respectively, mainly for element content and form value operations.

(1) Common element content html() (equivalent to native innerHTML)

html() // Get the content of an element
html("content") // Set the content of an element

(2) text() as normal element text content (comparable to native innerText)

text() // Get the text content of an element
text("Text Content") // Set the text content of an element

Note: html() recognizes tags, text() does not.

(3) Value val() (equivalent to native value)

Example:

val() // Get the value of the form
val("content") // Set the value of the form
<body>
    <div>
        <span>I am content</span>
    </div>
    <input type="text" value="Please enter content">
    <script>
        // 1. Get the setting element content html()
        console.log($("div").html());
        // $("div").html("123");
        // 2. Get text() for setting element text content
        console.log($("div").text());
        $("div").text("123");
        // 3. Get the set form value val()
        console.log($("input").val());
        $("input").val("123");
    </script>
</body>

6. jQuery Element Operation

JQuery element operations mainly focus on using jQuery methods to manipulate tag traversal, create, add, delete and other operations.

6.1 Traversing Elements

jQuery implicit iteration does the same thing for the same type of element. If you want to do different things for the same type of element, you need to use traversal.

(1) Grammar 1:

$("div").each(function (index, domEle) { xxx; })
  1. each() method traverses each matching element. It is mainly handled by the DOM. Each each.
  2. The callback function inside has two parameters: index is the index number of each element;demEle is each DOM element object, not a jquery object.
  3. So to use the jquery method, you need to convert this dom element to a jquery object $(domEle).

(2) Grammar 2:

$.each(object,function (index, element) { xxx; })
  1. The $.each() method can be used to traverse any object. It is mainly used for data processing, such as arrays, objects.
  2. The function inside has two parameters: index is the index number of each element;Elementment traverses content.

Note: This method is used to iterate through each item in the jQuery object, the element in the callback function is a DOM object, and conversion is required to use the jQuery method.

Example:

<body>
    <div>1</div>
    <div>2</div>
    <div>3</div>
    <script>
        $(function() {
            // Traversal elements are required if different operations are performed on the same type of element (similar to for, but more powerful than for)
            var sum = 0;
            var arr = ["red", "green", "blue"];
            // 1.Each() method traverses elements 
            $("div").each(function(i, domEle) {
                // The first parameter of the callback function must be the index number. You can specify the name of the index number yourself.
                // console.log(i);
                // The second parameter of the callback function must be a dom element object, named after itself
                // console.log(domEle); //Using the jQuery method requires a conversion of $(domEle)
                $(domEle).css("color", arr[i]);
                sum += parseInt($(domEle).text());
            })
            console.log(sum);
            // 2. $.each() method traversal element is mainly used to traverse data and process data
            // $.each($("div"), function(i, ele) {
            //     console.log(i);
            //     console.log(ele);
            // });
            // $.each(arr, function(i, ele) {
            //     console.log(i);
            //     console.log(ele);
            // })
            $.each({
                name: "andy",
                age: 18
            }, function(i, ele) {
                console.log(i); // The output is the name age attribute name
                console.log(ele); // The output is an Andy 18 attribute value
            })
        })
   </script>
</body>

6.2 Create Elements

Grammar:

$("<li></li>");

Dynamically created a <li>.

6.3 Add Elements

(1) Internal addition

element.append("content")

Place the content at the end of the matching element, similar to the native appendChild.

element.prepend("content")

Put the content first inside the matching element.

(2) External addition

element.after("content") // Place content behind the target element
element.before("content") // Place content in front of the target element

1. Add elements internally, and once generated, they are parent-child relationships.

(2) Externally added elements, after being generated, they are brothers.

6.4 Delete elements

element.remove() // Delete the matching element (itself) to commit suicide
element.empty() // Delete all child nodes in the matching element collection
element.html("") // Empty matching element content children

remove deletes the element itself.

(2) empt() and html(") are equivalent in effect, and can delete the contents of an element, but html can also set the contents.

Example:

<body>
    <ul>
        <li>Original li</li>
    </ul>
    <div class="test">I was the original div</div>
    <script>
        $(function() {
            // 1.Create Elements
            var li = $("<li>I created it later li</li>");
      
            // 2.Add Elements
            // 	2.1 Internal Add
            // $("ul").append(li);Add internally and put at the end of the content 
            $("ul").prepend(li); // Add internally and put at the top of the content
            //  2.2 External Add
            var div = $("<div>I was born to a stepmother</div>");
            // $(".test").after(div);
            $(".test").before(div);
      
            // 3.Delete element
            // $("ul").remove();Suicide by deleting matching elements
            // $("ul").empty(); //Child nodes inside matching elements can be deleted
            $("ul").html(""); // Child nodes inside matching elements can be deleted
        })
    </script>
</body>

7. jQuery size, position operation

7.1 jQuery size

grammarusage
width() / height()Gets the width and height of the matching element, only width / height
innerWidth() / innerHeight()Gets the width and height of the matching element, including padding
outerWidth() / outerHeight()Gets the width and height of the matching element, including padding, border
outerWidth(true) / outerHeight(true)Gets the width and height values of the matching elements, including padding, border, margin
  • If the above parameter is empty, the corresponding value is obtained and the number returned.
  • If the parameter is a number, the corresponding value is modified.
  • Parameters may not have to be written in units.
<body>
    <div></div>
    <script>
        $(function() {
            // 1.Width() / height() Gets the size of the setting elements width and height 
            console.log($("div").width());
            // $("div").width(300);

            // 2.InnerWidth() / innerHeight() Gets the size of the setting elements width and height + padding 
            console.log($("div").innerWidth());

            // 3.OuterWidth() / outerHeight() Gets the size of the setting elements width and height + padding + border 
            console.log($("div").outerWidth());

            // 4.OuterWidth (true) / outerHeight (true) get settings width and height + padding + border + margin
            console.log($("div").outerWidth(true));
        })
    </script>
</body>

7.2 jQuery Location

There are three main locations: offset(), position(), scrollTop()/scrollLeft().

(1) offset() sets or gets an element offset

The offset() method sets or returns the offset coordinates of the selected element relative to the document, regardless of the parent.

(2) The method has two attributes left and top.

  • offset().top is used to get the distance from the top of the document.
  • offset().left is used to get the distance from the left side of the document.

(3) The offset of the element can be set: offset ({top: 10, left: 30});

(2) position() to get the element offset

The position() method is used to return the coordinates of the selected element offset from its parent with positioning. If no parent is positioned, the document prevails.

(2) The method has two attributes left and top.

  • position().top is used to get the distance to locate the top of the parent.
  • position().left is used to get the distance to the left of the positioning parent.

(3) This method can only be obtained.

(3) scrollTop()/scrollLeft() Sets or gets the head and left side of the element that is rolled up

The scrollTop() method sets or returns the head of the selected element that has been rolled up.

(2) A number with no unit is set to the scrolled head.

<body>
    <div class="father">
        <div class="son"></div>
    </div>
        
    <div class="back">Return to top</div>
    <div class="container"></div>
   
    <script>
        $(function() {
            // 1.Gets the offset where the distance from the document is set (offset)
            console.log($(".son").offset());
            console.log($(".son").offset().top);
            // $(".son").offset({
            //     top: 200,
            //     left: 200
            // });
      
            // 2.Get distance with positioned parent location (offset) positionIf there is no positioned parent, the document prevails
            // This method can only get offsets that cannot be set
            console.log($(".son").position());
            // $(".son").position({
            //     top: 200,
            //     left: 200
            // });
      
      		// 3.Rolled Head
      		$(document).scrollTop(100);
            // scrollTop() of the curled head / left scrollLeft() of the curled head
            // Page Scroll Event
            var boxTop = $(".container").offset().top;
            $(window).scroll(function() {
                // console.log(11);
                console.log($(document).scrollTop());
                if ($(document).scrollTop() >= boxTop) {
                    $(".back").fadeIn();
                } else {
                    $(".back").fadeOut();
                }
            });
            // Return to top
            $(".back").click(function() {
                // $(document).scrollTop(0);
                $("body, html").stop().animate({
                    scrollTop: 0
                });
                // $(document).stop().animate({
                //     scrollTop: 0
                // };Animate html and body elements instead of documents
            })
        })
    </script>
</body>

Posted by scottlowe on Fri, 08 Oct 2021 10:03:27 -0700