JQuery

1. What is JQuery

  • JQuery is a fast and concise JavaScript framework. JQuery is set up to “write less,do more”, to do more with less code. It encapsulates common JavaScript functionality and provides a simple JavaScript design pattern that optimizes HTML document manipulation, event handling, animation design, and Ajax interaction.
  • JavaScript frameworks: Essentially js files that encapsulate native JS code.

2. Quick introduction to JQuery

2.1 one way

  • Download the JQuery.

  • Import jQuery js files: import min.js in

    < script SRC = "js/jquery - 3.3.1. Min. Js" > < / script >

    Notice the relative path here!

  • Use, write code

    There are three major versions of JQuery:

    1. X: compatible with IE678, the most widely used, the official only do bug maintenance, functionality is not added. So for general projects, use 1.x version.

    2. X: incompatible with IE678, few people only use official bug maintenance, functions are no longer added. You can use 2.x if you don’t consider compatible browsers with older versions.

    3. X: incompatible with IE678 and supports only the latest browsers. The 3.x version will not be used unless specifically requested, and many older JQuery plug-ins do not support this version. This is the current official major update maintenance version.

    Jquery-xxx.js is the same as jquery-xxx.min.js.

    1. Jquery-xxx. js: Development version. For programmers, with good indentation and comments. A little bit bigger
    2. Jquery-xxx.min. js: production version. Used in the program without indentation. Make it smaller. Faster program loading

2.2 way 2

  • Import using CDN

    / / baidu<head>
        <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
    </head>/ / sina<head>
        <script src="https://lib.sinaapp.com/js/jquery/2.0.2/jquery-2.0.2.min.js"></script>
    </head>Baidu jQuery CDN is okCopy the code
  • Use, write jQuery code

3. Basic syntax of jQuery

3.1 the formula

$(selector).action()

  • The dollar sign$Define the jQuery
  • selector(selector)Query and select HTML elements
  • action()Represents an operation performed on an element.

Understand the $3.2 (the function () {})

  • $(function () {} js code);The javascript function executes the JAVASCRIPT code after the HTML document is fully loaded. It is the jQuery entry function.
  • It is aThe $(document). Ready (function () {} js code);The shorthand.

Note: Window.onload is code in JS.

3.3 Differences and transformations between jQuery objects and JavaScript objects

  1. JQuery objects are much easier to manipulate

    <div id="div1">Text content...</div>
    <div id="div2">Text content...</div>Var divs = document.getelementsById ("div1"); Var divs2 =$("#div2");Copy the code
  2. JQuery object and JS object methods are not generic

  3. The two convert to each other

    Jq — > js: jq object [index] or Jq object.

    Js — > jq: $(js object)

How2j. Cn/k/jquery/jq…

4. The selector

4.1 role

  • Used to filter elements with the same characteristics

4.2 Review selectors in the DOM

// find by ID:

var a = document.getElementById(‘dom-id’);

// Select * from tag;

var divs = document.getElementsByTagName(‘div’);

/ / to find

:

var ps = document.getElementsByTagName(‘p’);

… .

This code is a bit cumbersome, and jQuery selectors can help you quickly locate one or more DOM nodes.

4.3 Search by ID


      
var div=$("#abc"); Copy the code

4.4 Search by Tag or Tag

var ps=$("p");// Return all 

nodes

ps.length;// Count how many

nodes the page has

Copy the code

4.5 Searching by class

var a=$(".red");// All nodes with class="red" are returned
/ / such as
//
      
...
//
...
Copy the code

4.6 Search by Attribute

  • A DOM node can have many attributes in addition to its ID and class. A lot of times it’s convenient to look up by attribute, such as in a form:
var email=$('[name=email]');/ / find the 
      
var passwordInput=$('[type=password]');/ / find the 
      
var a=$('[items="A B"]');/ / find the 
      
Copy the code
  • When the value of an attribute contains special characters, such as Spaces, use double parentheses.
  • Lookup by attribute can also use prefix lookup and suffix lookup
var icons=$('[name^=icon]');// Find the DOM with the name attribute value starting with icon
/ / such as name = "icon - 1," name = "icon - 2";
var names=$('[name$=with]');// Find all DOM whose name attribute value ends with
// For example: name="startswith",name="endswith"

Copy the code

4.7 Other important selectors

Refer to how2j:

How2j. Cn/k/jquery/jq…

5 operating DOM

5.1 Content Operation :Text/HTML/val

  • HTML (): Gets/sets the tag body content of the element.The content of the < a > < font > < / font > < / a >— >Content of the < font > < / font >
$("#d1").html();
// Get the element content through HTML, if there are child elements, keep the tag.
$("#d1").html("Textual content");
// The passed parameter becomes the setup text
Copy the code
  • Text (): Gets/sets the plain text content of the element’s tag body.The content of the < a > < font > < / font > < / a > – -> content
$("#d1").text();
// Get the content of the element, including no child element tags if there are any
$("#d1").text("Textual content");
// The passed parameter becomes the setup text
Copy the code
  • Val () : Gets/sets the value attribute of the element.
<input type="text" id="input1" value="Default value">
$("#input1").val();// Output value: default valueIs equivalent to:document.getElementById("input1").value;

$("#input1").val("Textual content");
// The passed parameter becomes the setup text
Copy the code

5.2 CSS Operations:

Elements are styled primarily through the following method apis.

  • AddClass () : addClass attribute value $(“#d”).addclass (“pink”);

  • RemoveClass () : removeClass attribute value ‘ ‘$(“#d”).removeclass (“pink”); `

  • ToggleClass () : toggleClass() : toggleClass(“pink”) : toggleClass() : toggleClass(“pink”);

    ToggleClass (“one”) : Removes the attribute value one if class=”one” exists on the element object. If class=”one” does not exist on the element object. Is added.

  • CSS () :

css(property,value); The first parameter is the style property, and the second parameter is the style value. css({p1:v1,p2:v2}); The arguments are pairs of attribute values contained in {}. Property value pairs`, `Split between attribute values` : `To separate attributes and values, use quotes like "$("#d1").css("background-color"."pink");
$("#d2").css({"background-color":"pink"."color":"green"});
Copy the code

5.3 CRUD on nodes

  1. Append (): Parent appends child elements to the end
  • Object 1. appEnd (object 2): Adds object 2 inside the element of object 1, and at the end
  1. Prepend (): the parent element appends the child element to the leading * object 1. Prepend (object 2): Appends object 2 inside the object 1 element and at the beginning

  2. AppendTo (): * Object 1.appendTo(object 2): adds object 1 inside object 2 and at the end

  3. PrependTo () : * Object 1. PrependTo (object 2): Add object 1 inside object 2, and at the beginning

  4. After (): Adds the element after the element

    * Object 1.after(object 2) : Appends object 2 to object 1. Object 1 and object 2 are siblingsCopy the code
  5. Before (): adds elements to the front of the element * object 1. Before (object 2) : adds object 2 to the front of object 1. Object 1 and object 2 are siblings

  6. InsertAfter () * object 1. InsertAfter (object 2) : Adds object 2 after object 1. Object 1 and object 2 are siblings

  7. InsertBefore () * object 1.insertBefore(object 2) : adds object 2 to the front of object 1. Object 1 and object 2 are siblings

  8. Remove (): removes the element * object. Remove (): removes the object

  9. Empty (): Empties out all descendants of the element.

  • Object. Empty (): Empties all descendants of the object, but preserves the current object and its attribute nodes

5.4 attributes of jquery Elements/Labels

  • Attr () : Gets/modifies the attributes of an element

  • RemoveAttr () : Removes the attributes of an element

<h1 id="h" align="center" game="LOL"> Center title </h1>/ / to get:
$("#h").attr("align")// The output is center
/ / modify
$("#h").attr("align"."right");// Set the property align to right
/ / delete
$("#h").removeAttr("align");// Delete the align attribute
Copy the code
  • Prop (): Gets/sets the attributes of the element
  • RemoveProp (): Removes attributes
$("#c").prop("game")// same as above.Copy the code
  • Attr differs from prop

    If you are working with inherent attributes of an element, prop is recommended

    Attr is recommended if you operate on elements’ custom attributes

5.5 Displaying and Hiding the DOM

  • The use of show and hide DOM elements is common, and jQuery provides show() and hide() methods directly.
<p>hello world</P>
var a=$("p");
a.hide();
a.show();
Copy the code
  • You can also set the display property of the CSS to display hidden elements, but this is not as convenient.

6. The jQuery animations

There are three ways to show and hide elements

  • Default display and hide modes.
1. show([speed,[easing],[fn]]) parameter: speed: the speed of the animation. Three predefined values ("slow","normal","fast") or milliseconds that represent the length of the animation. For example, 1000 easing: This is used to specify the switching effect. The default is "swing" and the parameter "Linear" is available. Swing: Animation execution is slow, fast in the middle, and slow at the end. Fn: a function that is executed at the completion of the animation, once for each element. 2. Hide ([speed,[easing],[fn]]) 3. Toggle ([speed],[easing],[fn])Copy the code
  • Slide show and hide
1. slideDown([speed],[easing],[fn])
2. slideUp([speed,[easing],[fn]])
3. slideToggle([speed],[easing],[fn])
Copy the code
  • Fade in and out show and hide
1. slideDown([speed],[easing],[fn])
2. slideUp([speed,[easing],[fn]])
3. slideToggle([speed],[easing],[fn])
Copy the code

7. Traversal

  1. Js traversal mode

    For (initialization value; Loop end condition; Step length)

  2. Jq traversal mode

    2.1 JQ Objects. Each (callback)

    Each (function(index,element){});

    Index: The index of an element in a collection

    Element: Each element object in a collection

    This: Each element object in the collection

    The return value of the callback function:

    True: If the current function returns false, the loop is broken.

    False: If the current function returns true, end this loop and continue the next loop (continue)

    $2.2 each (object, [callback])

    2.3 the for… Of jquery after version 3.0

    For (element object of container object)

Event 8.

8.1 Mouse Events

Mousedown means mousedown mouseup means mouseup mousemove: when the mouse enters the element, every move is called mouseenter: when the mouse enters the element, call it, move within it, Mouseover will not be called without calling its child: When the mouse enters an element, call it, move it around, Mouseleave is called when the mouse goes over its child. Mouseout is called when the mouse goes over its childCopy the code

8.2 Keyboard Events

Keydown: Triggered when the keyboard is pressed. Keyup: triggered when the keyboard is released. Keypress: triggered after the key is pressed onceCopy the code

8.3 Click Events

Dblclick () $(function(){$("#b").click(function(){$("#message").html("Click the button");
      });
      $("#b").dblclick(function(){$("#message").html("Double click button");
      });
  });
Copy the code

8.4 Loading Events

$(document).ready();
$(function(){}) -- - > the commonly used/ / for
<script>
  $(document).ready(function(){$("#message1").html("Page loaded successfully");
   
  });
  $(function(){$("#img").load(function(){$("#message2").html("Image loaded successfully");
    });
  });
</script>
<div id="message1"></div>
<div id="message2"></div>
<img id="img" src="https://how2j.cn/example.gif">
Copy the code

8.5 Binding Events

$("selector").on("event".function);// Bind events

$(function(){$("#b").on("click".function(){$("#message").html("Click the button");
      });
      $("#b").on("dblclick".function(){$("#message").html("Double click button");
      });
  });

$("selector").off("event");// Unbind

Copy the code

8.6 Other important events

How2j. Cn/k/jquery/jq…

9. The plugin

Implementation method:

1.$.fn.extend(object) * Enhance the function of objects obtained through Jquery $("#id")
2.$.extend(object) * Enhances the function of the JQeury object itself $/jQueryCopy the code

www.runoob.com/jquery/jque…