JQ notes


JQ objects and DOM objects are interchangeable

DOM->jQ: $(DOM object)

$('div')
Copy the code

2. JQ objects are converted to DOM objects (in two ways):

(1) $(' div ') [index], the index is 0 (2) $(' div '). The get (index), the index is the index numberCopy the code

The jQ level selector is identical to the CSS level selector


JQ objects cannot use style because it belongs to jQ objects, not DOM objects


Implicit iteration:

JQ internally loops through all matched elements, adding CSS to each elementCopy the code

JQ filters the selector

:first

:last

:eq(index)

:odd

:even


JQ screening method

Parent () Parent of the nearest level

Children (selector) only finds the closest son -> the closest son, equivalent to ul>li

Find (selector) finds all elements that match the selector

Siblings find siblings, excluding siblings

NextAll () finds all subsequent peers

PrevAll () finds all previous peers

HasClass (class) checks whether the current element contains a particular class and returns true if it does

Eq (index) is equivalent to $(“li:eq(2)”), and index starts at 0. This method is preferred, and variables can be inserted without concatenating strings


JQ Idea of exclusion:

Uses implicit iteration implementation ->siblings(selector) to find siblings, excluding themselvesCopy the code

JQ chain programming

A bit like Java streaming programming, you can always point out what's really changing, otherwise it's easy to make mistakesCopy the code

JQ Method of modifying and manipulating the CSS

$("div").css("width", 300); $("div").css({width: 400, heigth: 400, backgroundColor: "red");Copy the code

JQ modify style operation class, do not operate CSS files as far as possible, directly add classes with jQ, very convenient

1. Add class addClass () $(" div "). Click (function () {$(this). The addClass (" current "); }); RemoveClass removeClass()... ToggleClass ("current"); Transform: Rotate (360deg) Rotate 360°Copy the code

The jQ class operates differently from className

The className in native js overrides the original className of the element. JQ only operates on the specified class, not the original className.Copy the code

JQ Effects: Encapsulates many effects

  • Show hide: show()/hide()/toggle();
  • Draw: slideDown()/slideUp()/slideToggle();
  • FadeIn and out: fadeIn()/fadeOut()/fadeToggle()/fadeTo();
  • Custom animation: animate();

Note:

Animations or effects are executed once triggered, and if triggered more than once, multiple animations or effects are queued to execute. JQuery gives us another way to stop animation queuing: stop();

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

1.show([speed,[easing],[fn]]) 2.hide([speed,[easing],[fn]]) 3.toggle([speed,[easing],[fn]]) speed: Slow normal fast or milliseconds easing: The default swing is linear FN: the callback is availableCopy the code

In general, no need to hide or switch directly on the line


Slide:

slideDown() / slideUp() / slideToggle()

The parameters are exactly the same as the above three


Event switching:

1. Hover is a combination of mouse over and away -> view 05.htmlCopy the code

Animation queue and its method of stopping queuing

1. Animation or effect queue

2. Stop queuing: Stop the animation that is triggered repeatedly in a short time, and only execute the last.stop()


Fade in and out effect

The fadeIn()/fadeOut()/fadeToggle()/fadeTo() arguments are the same as the above…

Adjust transparency:

fadeTo([[speed],opactity,[easing],[fn]])
Copy the code

Opacity is between 0 and 1


Custom Animate

Animate (Params,[speed],[easing],[fn]) 1. Params: Style properties that you want to change, passed as objects, must be written. Attribute names can be quoted as aboveCopy the code

Case: King accordion case


JQ property operation

  1. Prop (): Gets or sets the intrinsic value of an element, using prop()

    Note: the return value of prop() is Boolean

    Such as: the href inside the < a >, < input > inside type * access: $(" a ".) prop (" href "); * Set: $("a").prop("href","www.baidu.com"); Add:.change([fn]) method: when an object changes, the callback function can be calledCopy the code
  2. Attr (” attribute “): To get the element’s custom attributes we use attr(” attribute “) // similar to native getAttribute()

    Attr (" attribute "," attribute value ") // Like native setAttribute()Copy the code

    You can also get the original H5 custom attributes

Data () contains data stored in the element’s memory

H5: data index h5: data index h5: data index h5: data index h5: data index h5: data index h5: data indexCopy the code

JQ All selected cases

Ideas:

  1. The checked state of the three small checkbox buttons follows that of the full check button

  2. Checked is an inherent property of the check box, which requires the prop() method to get and set

  3. Assign all button status to three small check boxes

  4. Each time we click the little checkbox button, we judge:

  5. If the number of small checkboxes is equal to n(3), the all button should be selected, otherwise the All button is not selected

  6. : Checked selector: Checked to find the selected form element


JQ content text value

1. Get/set -> Normal element content HTML () —–> equivalent to.innerhtml (note: attributes come from)

.html() [gets] content.html (" content ") [sets] the content of the elementCopy the code

2. Get/set -> Plain element text content text() —–> equivalent to.innertext

.text() [gets] the text content of the element. Text (" Text content ") [sets] the text content of the elementCopy the code

3. Get/set -> form value val() —–> equivalent to native.value

console.log($("input").val());
$("input").val("123");
Copy the code

JQ case

Shopping cart, increase or decrease the quantity of goods

1. Declare a variable, when clicked on increment, add the value ++ and assign it to the textbox

2. Note: Can only increase the quantity of this product, is the current + sibling text box (ITXT) value

3. The value of the form is changed by the val() method

4. Note: The initial value of this variable should be the value of the text box, based on this value ++, so we need to get the form value before ++

5. The minus signs should be the same, but not less than 1

Details:.val() returns a string of type. If === =, it will always be false.Copy the code

Shopping cart: subtotal function

1. Each time you click the + sign or – sign, multiply the value of the text box by the current price of the product, which is the subtotal of the product

2. Only the subtotal of goods can be increased, that is, the subtotal module of the current goods (P-sum).

3. The text() method is used to modify the contents of a common element

4. The current price of the product, to remove the ¥sign and multiply, cut the string substr(1)

4.1. Add content

5. Parents (‘ selector ‘) can return the specified ancestor element.

6. The final result can be calculated using.tofixed (2) to preserve two decimal places

7. Users can also directly modify the values in the form, and also calculate subtotals

8. Multiply the unit price by [the value in the latest form], but it is still the subtotal of the current item


JQ element operation

1. Iterate over elements

$(“selector”).each()

JQ implicit iteration does the same operation on the same class of elements, and if you want to do different operations on the same class of elements, you need to traverse

$("div").each(function(index, domEle){ xxx; . }); $(domEle); $(domEle); $(domEle); $(domEle);Copy the code

2. Traversal element method 2, mainly used for traversal data, and [[processing data]]

$. Each (function(I, ele){XXX; . });Copy the code

3. Create elements

$("<li></li>"); Dynamically create a <li>Copy the code

4. Add elements

Internal add

Add.append() and.prepend() firstCopy the code

External add: Put before & after the target element

After (" content ") before(" content ") Inner add is parent-child and outer add is siblingCopy the code

5. Delete elements

Element.remove () removes the matching element (itself)

Element.empty () removes all subslots in the matching set of elements

Element.html (“”) clears the matched element content


JQ case: Calculate totals and amounts

1. Add the values in all text boxes to get the total number, and the same goes for the total number

2. The values in the text box are different, so if you want to add them, use each to iterate, declare a variable, and add them

3. Click the +- sign to change the total and total, the above two operations can call this function

4. Note:

The total is the sum of the values in the text box, val(); The total is the normal element content, text();Copy the code

5. Also pay attention to type conversions


JQ Case: Select an item and add a background

Ideas:

1. Add a background to the selected item. If no background is selected, remove the background

2. Select all button click: If select all, add background for all goods, otherwise remove background

3. Small check box: if it is selected, add background to the current item, otherwise remove background


Event registration

Single event registration

$("div").click(function(){event handler}); Mouseover mouse moves in, mouseout mouse moves out, blur loses focus, focus gains focus, change value changes, KeyDown is pressed, KeyUp is reloaded, resize changes, Scroll barCopy the code

The event processing

JQ use. On (events, [the selector], [data], fn)

An event handler that binds one or more events to a selection element.

Event binding: Event handlers to elements in the currently selected jQuery object. On () method

Primary processing $1. Events (" div "). Click (function () {$(this). The CSS (" background ", "pink"); }); $("div").on({mouseenter: function () {$(this).css("background", "skyblue"); $(this).css("background", "skyblue"); }, click: function () { $(this).css("background", "purple"); }, mouseleave: function () { $(this).css("background", "blue"); }}); $(function () {$("div").on(" mouseEnter mouseleave"); $(function () {$("div").on(" mouseEnter mouseleave") function () { $(this).toggleClass("current"); }); }); $("ul"). On ("click","li",function(){alert("hello ",function(){alert("hello ") world!" ); }); $("ol li").click(function (); $("ol li").click(function ());  { alert(11); }); Use. On () can include elements, created on the fly, $(" ol ") on (" click ", "li", function () {alert (11); }); Let li = $("<br><li> </li>"); $("ol").append(li); $(function () {/ / 1. Click on the release, dynamically create a small li, add the content of the text box and delete button, and added to the ul $(" BTN ") on (" click ", function () {let li = $(" < li > < / li > "); li.html($(".txt").val() + "<a href='javascript:; '> delete < / a > "); $("ul").prepend(li); li.slideDown(); $(".txt").val(""); }); // If you want to add an event to the parent element, you can add an event to the child element. If you want to add an event to the parent element, you can add an event to the child element. $("selector").on([event], [element], [fu]); * / $(" ul ") on (" click ", "a", function () {/ / a father is li $(this). The parent (). The slideUp (function () {$(this). The remove (); }); }); });});});Copy the code

Event unbundling

$("div").on({ mouseenter: function () { $(this).css("background","purple"); }, mouseleave: function (){ $(this).css("background","green"); }}); $("ul").on("click", "li", function () { alert(111); }) / / event unbundling. Off () / / 1. No pass parameters, remove all the events / / $(" div ") off (); $("div").off("click"); $("ul"). Off ("click", "li"); / / 4. One () event can trigger a $(" p "). One (" click ", function () {alert (11); });Copy the code

Automatic trigger event trigger()


The event object