JavaScript personal learning notes Summary - jQuery

Posted by jvanv8 on Tue, 08 Mar 2022 14:32:37 +0100

JavaScript personal learning notes Summary - quick start
JavaScript personal learning notes Summary - function
JavaScript personal learning notes Summary - standard object
JavaScript personal learning notes Summary - object oriented programming
JavaScript personal learning notes Summary - browser
JavaScript personal learning notes Summary - jQuery
Updating ingUpdating ing


  • jQuery is a JavaScript library.
  • The so-called library is a JS file, which encapsulates many predefined functions, such as obtaining elements, performing hiding, moving, etc. The purpose is to call directly when in use without repeated definition, which can greatly simplify JavaScript programming.
  • jQuery official website:

  jQuery is so popular because it solves some important problems. In fact, jQuery can help us do these things:

  • Eliminate browser differences: you don't need to write lengthy code to bind events for different browsers and write AJAX and other code;
  • A concise way to manipulate DOM: writing $('#test') is definitely better than document Getelementbyid ('test ') is concise;
  • Easily realize animation, modify CSS and other operations.

   the concept of jQuery "Write Less, Do More" allows you to write less code and complete more work!

   to use jQuery, you only need to import the jQuery file in < head > of the page.


    $is the famous jQuery symbol. In fact, jQuery encapsulates all functions in a global variable jQuery, and $is also a legal variable name, which is the alias of variable jQuery:

	window.jQuery; // jQuery(selector, context)
	window.$; // jQuery(selector, context)
	$ === jQuery; // true
	typeof($); // 'function'

    $is essentially a function, but the function is also an object, so $can have many other properties in addition to being called directly.

You can change the name of the $query function (j8195a) and the name of the $query function (j8195b), because you can see that many of the parameters of the $query function may not be the name of the JavaScript function (j8195a, j81b).

  most of the time, we use $(because it's easier to write). However, if the $variable is unfortunately occupied and cannot be changed, we can only ask jQuery to hand in the $variable, and then we can only use the jQuery variable:

	$; // jQuery(selector, context)
	$; // undefined
	jQuery; // jQuery(selector, context)

   the principle of this dark magic is that jQuery saves the original $internally before occupying $and calls jQuery Noconflict() will restore the original saved variables.

Quick start:

  1. Write HTML documents.
  2. Import jQuery file.
  3. Use jQuery to get elements.
  4. Test with browser
    // JS mode, get div element through id attribute value
    let jsDiv = document.getElementById("div");
   // alert(jsDiv.innerHTML);

    // jQuery method, get div element through id attribute value
    let jqDiv = $("#div");
    // Get the value of element id through JS div attribute
    let jsDivs = document.getElementsByTagName("div");

    // jQuery method, get div element through id attribute value
    let jqDiv = $("#div");//


1. Selector

  selectors are the core of jQuery. A selector is written like $('#dom-id').

// Find by ID:
var a = document.getElementById('dom-id');

// Find by tag:
var divs = document.getElementsByTagName('div');

// Find < p class = "red" >:
var ps = document.getElementsByTagName('p');
// Filter out class="red":
// TODO:

// Find all < tr > in < table class = "green" >:
var table = ...
for (var i=0; i<table.children; i++) {
    // TODO: filter out < tr >

   these codes are too cumbersome, and in the hierarchical relationship, for example, finding all the loops in < table class = "green" > is actually wrong, because the standard writing of < Table >:


  many times, you need to recursively find all child nodes.

  the selector of jQuery is to help us quickly locate one or more DOM nodes.

Find by ID

   if a DOM node has an id attribute, use jQuery to find the following:

// Find < div id = "ABC" >:
var div = $('#abc');

    note that # abc begins with #. The returned object is a jQuery object.

  what is a jQuery object? A jQuery object is similar to an array, and each element of it is an object that references a DOM node.

   take the above search as an example. If < div > with id abc exists, the returned jQuery objects are as follows:

[<div id="abc">...</div>]

   if < div > with id abc does not exist, the returned jQuery object is as follows:


   in short, the selector of jQuery will not return undefined or null. The advantage is that you don't have to judge if (div === undefined) on the next line.

  jQuery objects and DOM objects can be converted to each other:

var div = $('#abc'); // jQuery object
var divDom = div.get(0); // Assuming div exists, get the first DOM element
var another = $(divDom); // Repackage the DOM as a jQuery object

  generally, you don't need to get DOM objects. It's more convenient to use jQuery objects directly. If you get a DOM object, you can simply call $(aDomObject) to turn it into a jQuery object, so you can easily use the jQuery API.

Find by tag

   press tag to find. Just write the tag name:

var ps = $('p'); // Return all < p > nodes
ps.length; // Count the number of < p > nodes on the page

Find by class

   search by class. Note: add a. Before the class name:

var a = $('.red'); // All nodes containing ` class="red" ` will be returned
// For example:
// <div class="red">...</div>
// <p class="green red">...</p>

  usually, many nodes have multiple class es. We can find nodes that contain both red and green:

var a = $(''); // Note that there are no spaces!
// Qualified nodes:
// <div class="red green">...</div>
// <div class="blue green red">...</div>

Find by attribute

   besides id and class, a DOM node can also have many attributes. It is very convenient to find by attributes in many cases, such as finding by attributes in a form:

var email = $('[name=email]'); // Find out <??? name="email">
var passwordInput = $('[type=password]'); // Find out <??? type="password">
var a = $('[items="A B"]'); // Find out <??? items="A B">

   when the value of the attribute contains special characters such as spaces, it needs to be enclosed in double quotation marks.

   search by attribute can also use prefix search or suffix search:

var icons = $('[name^=icon]'); // Find all DOM whose name attribute value starts with icon
// For example: name="icon-1", name="icon-2"
var names = $('[name$=with]'); // Find all DOM S whose name attribute values end with with
// For example: name = "startswitch", name = "endswitch"

   this method is especially suitable for searching through the class attribute and is not affected by the fact that the class contains multiple names:

var icons = $('[class^="icon-"]'); // Find out that all class es contain at least one DOM starting with 'icon -'
// For example: class = "icon clock", class = "ABC icon home"

Combined search

Combined search is to combine the above simple selectors. If we search $('[name=email]'), we may find < div name = "email" > outside the form, but we only want to find < input >, so we can write:

var emailInput = $('input[name=email]'); // Will not find < div name = "email" >

Similarly, it is also common to combine search based on tag and class:

var tr = $(''); // Find < tr class = "red..." ></ tr>

Multinomial selector

Multiple selectors are used to combine multiple selectors into one piece:

$('p,div'); // Select both < p > and < div >
$(','); // Select both < p class = "red" > and < p class = "green" >

  note that the selected elements are arranged in the order they appear in HTML, and there will be no duplicate elements. For example, < p class = "red green" > will not be selected twice by the above $(', ').

1.1 level selector

    // 1. Offspring selector $("a, B"); All B under a (including children and grandchildren of B)
    let spans1 = $("div span");

    // 2. Sub selector $("a > b"); All B under a (excluding children of B, only sons)
    let spans2 = $("div > span");

    // 3. Brother selector $("a + B"); A is next to B
    let ps1 = $("div + p");

    // 4. Brother selector $("a ~ B"); A all B of the same level (lower side)
    let ps2 = $("div ~ p");

   if the two DOM elements have a hierarchical relationship, you can use $('ancestor descendant ') to select, and the levels are separated by spaces. For example:

<!-- HTML structure -->
<div class="testing">
    <ul class="lang">
        <li class="lang-javascript">JavaScript</li>
        <li class="lang-python">Python</li>
        <li class="lang-lua">Lua</li>

To select JavaScript, use the level selector:

$('ul.lang li.lang-javascript'); // [<li class="lang-javascript">JavaScript</li>]
$('div.testing li.lang-javascript'); // [<li class="lang-javascript">JavaScript</li>]

   because < div > and < UL > are the ancestor nodes of < li >, the corresponding < li > nodes can be selected in the above two methods.

  to select all < li > nodes, use:

$('ul.lang li');

   the advantage of this hierarchical selector over a single selector is that it reduces the selection range, because the parent node must be located before the corresponding child node can be selected, which avoids other irrelevant elements of the page.

For example:

$('form[name=upload] input');

  limit the selection range to the form whose name attribute is upload. If the page has many forms, < input > of other forms will not be selected.

  multi layer selection is also allowed:

$('form.test p input'); // Select the < input > included by < p > in the form

Child Selector

   sub selector $('parent > child ') is similar to the level selector, but it limits that the level relationship must be parent-child relationship, that is, the < child > node must be the direct child node of the < parent > node. Let's take the above example:

$('ul.lang>li.lang-javascript'); // You can select [< Li class = "Lang JavaScript" > JavaScript < / Li >]
$('div.testing>li.lang-javascript'); // [] cannot be selected because < div > and < li > do not constitute a parent-child relationship


   filters are generally not used alone. They are usually attached to selectors to help us locate elements more accurately. Observe the effect of the filter:

$('ul.lang li'); // Select three nodes: JavaScript, Python and Lua

$('ul.lang li:first-child'); // Select JavaScript only
$('ul.lang li:last-child'); // Only Lua is selected
$('ul.lang li:nth-child(2)'); // Select the nth element. N starts from 1
$('ul.lang li:nth-child(even)'); // Select the elements with even numbers
$('ul.lang li:nth-child(odd)'); // Select the elements with odd numbers

Form related

jQuery also has a special set of selectors for form elements:

  • : input: you can select < input >, < textarea >, < Select > and < button >;
  • : File: you can select < input type = "file" >, which is the same as input[type=file];
  • : checkbox: you can select a checkbox, which is the same as input[type=checkbox];
  • : Radio: you can select a radio box, which is the same as input[type=radio];
  • : focus: you can select the element of the current input focus. For example, place the cursor on a < input > and select it with $('input:focus');
  • : checked: select the currently checked radio box and check box. With this selector, you can immediately obtain the items selected by the user, such as $('input[type=radio]:checked ');
  • : enabled: you can select < input >, < Select >, etc. that can be input normally, that is, the input without graying out;
  • : disabled: in contrast to: enabled, select those that cannot be entered.

In addition, jQuery has many useful selectors, such as selecting visible or hidden elements:

$('div:visible'); // All visible div
$('div:hidden'); // All hidden div

1.2 filter selector

    // 1. First element selector 	$ ("A:first");
    let div1 = $("div:first");
    alert(div1.html());                 //div1

    // 2. Tail element selector 	$ ("A:last");
    let div4 = $("div:last");
    alert(div4.html());                 //div4

    // 3. Non element selector 	$ ("A:not(B)");
    let divs1 = $("div:not(#div2)");
    alert(divs1.length);                //3

    // 4. Even selector 	    $ ("A:even");
    let divs2 = $("div:even");  
    alert(divs2.length);                //2
    alert(divs2[0].innerHTML);          //div1
    alert(divs2[1].innerHTML);          //div3

    // 5. Odd selector 	    $ ("A:odd");
    let divs3 = $("div:odd");
    alert(divs3.length);                //2
    alert(divs3[0].innerHTML);          //div2
    alert(divs3[1].innerHTML);          //div4

    // 6. Equal to index selector 	 $ ("A:eq(index)");
    let div3 = $("div:eq(1)");   // equals

    // 7. Greater than index selector 	 $ ("A:gt(index)");
    let divs4 = $("div:gt(1)"); //

    // 8. Less than index selector 	 $ ("A:lt(index)");
    let divs5 = $("div:lt(2)");
    // alert(divs5.length);
    // alert(divs5[0].innerHTML);
    // alert(divs5[1].innerHTML);
    //9 multiple mixed use

1.3 basic selector

  • Selectors: selectors similar to CSS can help us get elements.
  • For example: id selector, class selector, element selector, attribute selector, and so on.
  • Syntax of selector in jQuery: $();

    //1. Element selector $("name of element")
    let divs = $("div");

    // selector $("#id attribute value")
    let div1 = $("#div1");

    //3. class selector $("attribute value of. class")
    let cls = $(".cls");

1.4 attribute selector

    //1. Attribute name selector $("element [attribute name]")
    let in1 = $("input[type]");

    //2. Attribute value selector $("element [attribute name = attribute value]")
    let in2 = $("input[type='password']");

1.5 form attribute selector

    // 1. Available element selector $("A:enabled");
    let ins1 = $("input:enabled");

    // 2. Unavailable element selector $("A:disabled");
    let ins2 = $("input:disabled");

    // 3. Element with radio / check box selected $("A:checked");
    let ins3 = $("input:checked");

    // 4. The selected element in the drop-down box is $("A:selected");
    let select = $("select option:selected");

2. Operation DOM

Modify Text and HTML

The text and HTML structures of the jQuery () node, for example, are as follows:

<!-- HTML structure -->
<ul id="test-ul">
    <li class="js">JavaScript</li>
    <li name="book">Java &amp; JavaScript</li>

Get text and HTML respectively:

$('#test-ul li[name=book]').text(); // 'Java & JavaScript'
$('#test-ul li[name=book]').html(); // 'Java &amp; JavaScript'

   a jQuery object can contain 0 or any DOM object, and its method will actually act on each corresponding DOM node. Try in the above example:

$('#test-ul li').text('JS'); //  Have both nodes become JS?

  so another advantage of jQuery object is that we can perform an operation on the corresponding set of DOM nodes. Even if the selector does not return any DOM nodes, the method calling the jQuery object will still not report an error:

// If there is no node with id not exist:
$('#not-exist').text('Hello'); //  No error is reported in the code, and no node is set to 'hello'

    this means that jQuery helps you avoid many if statements.

Modify CSS

   jQuery objects have the characteristics of "batch operation", which is very convenient for modifying CSS. Consider the following HTML structure:

<!-- HTML structure -->
<ul id="test-css">
    <li class="lang dy"><span>JavaScript</span></li>
    <li class="lang"><span>Java</span></li>
    <li class="lang dy"><span>Python</span></li>
    <li class="lang"><span>Swift</span></li>
    <li class="lang dy"><span>Scheme</span></li>

  to highlight the dynamic language, call the css('name ',' value ') method of the jQuery object.

   note that all methods of jQuery object return a jQuery object (which may be new or itself), so that we can make chain calls, which is very convenient.

The css() method of jQuery object can be used as follows:

var div = $('#test-div');
div.css('color'); // '#000033', get CSS properties
div.css('color', '#336699'); //  Set CSS properties
div.css('color', ''); // Clear CSS properties

  in order to be consistent with JavaScript, CSS properties can be in the formats of 'background color' and 'backgroundColor'.

The   css() method will act on the style attribute of the DOM node with the highest priority. If you want to modify the class attribute, you can use the following methods provided by jQuery:

var div = $('#test-div');
div.hasClass('highlight'); // false, whether the class contains highlight
div.addClass('highlight'); // Add the highlight class
div.removeClass('highlight'); // Delete the highlight class

Show and hide DOM

  to hide a DOM, we can set the display attribute of CSS to none and use the css() method. However, to display the DOM, you need to restore the original display attribute. First, you have to write down whether the original display attribute is block, inline or other values.

  considering that displaying and hiding DOM elements are very common, jQuery directly provides show() and hide() methods. We don't care how it modifies the display attribute. In short, it works normally:


ar a = $('a[target=_blank]');
a.hide(); // hide; // display

  note that hiding DOM nodes does not change the structure of the DOM tree, it only affects the display of DOM nodes. This is different from deleting DOM nodes.

Get DOM information

   using several methods of jQuery object, we can directly obtain the height, width and other information of DOM without writing specific code for different browsers:

	// Browser visible window size:
	$(window).width(); // 800
	$(window).height(); // 600

	// HTML document size:
	$(document).width(); // 800
	$(document).height(); // 3500

	// Size of a div:
	var div = $('#test-div');
	div.width(); // 600
	div.height(); // 300
	div.width(400); // Set the CSS property width: 400px. Whether it takes effect depends on whether the CSS is valid
	div.height('200px'); // Set the CSS attribute height: 200px. Whether it takes effect depends on whether the CSS is valid

The attr() and removeAttr() methods are used to manipulate the properties of DOM nodes:

	// <div id="test-div" name="Test" start="1">...</div>
	var div = $('#test-div');
	div.attr('data'); // undefined, attribute does not exist
	div.attr('name'); // 'Test'
	div.attr('name', 'Hello'); // The name attribute of div changes to 'Hello'
	div.removeAttr('name'); // Delete name attribute
	div.attr('name'); // undefined

The   prop() method is similar to attr(), but HTML5 stipulates that there is an attribute that can have no value in the DOM node. There are only two kinds: occurrence and non occurrence, for example:

<input id="test-radio" type="radio" name="test" checked value="1">

Equivalent to:

<input id="test-radio" type="radio" name="test" checked="checked" value="1">

attr() and prop() differ in the handling of checked attributes:

var radio = $('#test-radio');
radio.attr('checked'); // 'checked'
radio.prop('checked'); // true

The return value of prop() is more reasonable. However, it is better to use the is() method:

var radio = $('#test-radio');':checked'); // true

Similar attributes include selected. It is better to use is(':selected') when processing.

Operation form

   for form elements, jQuery objects uniformly provide val() method to obtain and set the corresponding value attribute:

    	<input id="test-input" name="email" value="">
    	<select id="test-select" name="city">
        	<option value="BJ" selected>Beijing</option>
        	<option value="SH">Shanghai</option>
        	<option value="SZ">Shenzhen</option>
    	<textarea id="test-textarea">Hello</textarea>
    	input = $('#test-input'),
    	select = $('#test-select'),
    	textarea = $('#test-textarea');

	input.val(); // 'test'
	input.val(''); // The content of the text box has changed to

	select.val(); // 'BJ'
	select.val('SH'); // The selection box has changed to Shanghai

	textarea.val(); // 'Hello'
	textarea.val('Hi'); // Text area updated to 'Hi'

   it can be seen that a val() unifies the value and assignment of various input boxes.

2.1 modify DOM structure


  to add a new DOM node, you can use the append() method in addition to the html() method of jQuery, for example:

<div id="test-div">

How to add a language to the list? First get the < UL > node:

var ul = $('#test-div>ul');

Then, call append() to import the HTML fragment:


   in addition to accepting strings, append() can also pass in original DOM objects, jQuery objects and function objects:

// To create a DOM object:
var ps = document.createElement('li');
ps.innerHTML = '<span>Pascal</span>';
// To add a DOM object:

// Add jQuery object:

// Add function object:
ul.append(function (index, html) {
    return '<li><span>Language - ' + index + '</span></li>';

   when passing in a function, it is required to return a string, DOM object or jQuery object. Because jQuery's append() may act on a group of DOM nodes, only the incoming function can generate different child nodes for each dom.

append() adds the DOM to the end, and prepend() adds the DOM to the top.

   also note that if the DOM node to be added already exists in the HTML document, it will be removed from the document first and then added. That is, you can move a DOM node with append().

   if you want to insert a new node into a specified location, for example, between JavaScript and Python, you can first locate JavaScript and then use the after() method:


 js = $('#test-div>ul>li:first-child');

That is, peer nodes can use after() or before() methods.

Delete node

  to delete the DOM node, just call the remove() method directly after you get the jQuery object. If the jQuery object contains several DOM nodes, you can actually delete multiple DOM nodes at once:

var li = $('#test-div>ul>li');
li.remove(); // All < li > are deleted

2.2 operation text

     //1. html() gets the text content of the tag
         //Get the text content of div tag
         let value = $("#div").html();

     //2. html(value) sets the text content of the tag and parses the tag
         //Set the text content of div label
         //$("#div").html("I'm really div");
       //  $("#div"). HTML ("< b > I'm really div < / b >");

        let username = $("#username").val();


2.3 operation object

    let p=$("p");
     let p= $("<p>abc<p>");

        1. $("Element '') creates the specified element
        // Add water to the cup
        // Add water to the cup
        // Father son relationship
        2. append(element)   Added as the last child element, called by the adder object
        3. appendTo(element) Added as the last child element, which is called by the added object
        4. prepend(element)  Added as the first child element, called by the adder object
        5. prependTo(element) Added as the first child element, called by the added object
        // Brotherhood
        6. before(element)    Added to the front of the current element. There is a sibling relationship between them, which is called by the adder object
        7. after(element)     Added to the back of the current element. There is a sibling relationship between them, which is called by the adder object
        8. remove()           Delete the specified element (remove yourself, commit suicide)
        9. empty()            Clear all child elements of the specified element (Wu Zetian)
    // Button 1: add a span to div
        let span = $("<span>span</span>");

    //Button 2: add refueling to the bottom of the city list

    //Button 3: add refueling to the top of the city list

    //Button 4: add Xiongqi to the bottom of Shanghai

    //Button 5: add Xiongqi to the top of Shanghai

    //Button 6: delete Xiongqi

    //Button 7: delete all description lists

2.4 operation style

    // 1.css(name) get css Style

    // 2.css(name,value) set CSS Style

    // 3.addClass(value) adds the style class name to the specified object

    // 4.removeClass(value) deletes the style class name for the specified object

    // 5.toggleClass(value) if there is no style class name, add. If yes, delete

2.5 operation attributes

    // 1.attr(name,[value]) gets / sets the value of the attribute
    //Button 1: get the id attribute of the input box
    //Button 2: set the value attribute to the input box

    // 2.prop(name,[value]) gets / sets the value of the attribute (checked, selected)
    //Button 3: select female

    //Button 4: select undergraduate

3. Events

   event refers to that when some components perform some operations, it will trigger the execution of some codes.

  • Common events

  • Understand events

    Binding event
  • Mode 1

Bind through the event attribute in the tag.

<button id="btn" onclick="Functions performed"></button>
  • Mode 2

Binding through DOM element attributes.

document.getElementById("btn").onclick = Functions performed


  • Mouse event

  click: triggered when the mouse clicks;
   dblclick: triggered when the mouse double clicks;
  mouseenter: triggered when the mouse enters;
   mouseleave: triggered when the mouse is removed;
   mousemove: triggered when the mouse moves inside the DOM;
   hover: two functions are triggered when the mouse enters and exits, which is equivalent to mouseenter plus mouseleave.

  • Keyboard events

Keyboard events only act on the DOM of the current focus, usually < input > and < textarea >.

   keydown: triggered when the keyboard is pressed;
   keyup: triggered when the keyboard is released;
  keypress: triggered after pressing the key once.

  • Other events

   focus: triggered when DOM obtains focus;
   blur: triggered when DOM loses focus;
   change: triggered when the content of < input >, < Select > or < textarea > changes;
   submit: triggered when < form > is submitted;
  ready: triggered when the page is loaded and the DOM tree is initialized.

The   ready object only works on   document. Since the ready event is triggered only once after the DOM completes initialization, it is very suitable for writing other initialization codes. Suppose we want to bind the submit event to a < form > form. The following code has no expected effect:

        // Wrong code:
        $('#testForm).on('submit', function () {
    <form id="testForm">

    because < form > has not been loaded into the browser when JavaScript is executed here, $('#testForm) returns [], and no event is bound to any DOM.

  therefore, our own initialization code must be placed in the ready event of the document object to ensure that the DOM has completed initialization:

        $(document).on('ready', function () {
            $('#testForm).on('submit', function () {
    <form id="testForm">

  there will be no problem in writing this way. Because the relevant code will be executed after the DOM tree is initialized.

   since the ready event is widely used, it can be simplified as follows:

$(document).ready(function () {
    // on('submit', function) can also simplify:
    $('#testForm).submit(function () {

It can even be simplified to:


(function () {
    // init...

   this kind of writing above is the most common. If you encounter $(function() {...}) Remember that this is the ready event handler of the document object.

   event handling functions can be bound repeatedly, and they will execute in turn:

	$(function () {
    	console.log('init A...');
	$(function () {
    	console.log('init B...');
	$(function () {
    	console.log('init C...');
  • Event parameters

  for some events, such as mousemove and keypress, we need to obtain the values of mouse position and keys, otherwise it is meaningless to listen to these events. All events will be passed into the Event object as parameters. You can get more information from the Event object:

	$(function () {
    	$('#testMouseMoveDiv').mousemove(function (e) {
        	$('#testMouseMoveSpan').text('pageX = ' + e.pageX + ', pageY = ' + e.pageY);
  • Unbind

A bound event can be unbound through off('click', function):

	function hello() {
	}; // Binding event

	// Unbind after 10 seconds:
	setTimeout(function () {'click', hello);
	}, 10000);

It should be noted that the following wording is invalid:

	// Binding event: () {

	// Unbind:'click', function () {

This is because as like as two peas anonymous functions, the two anonymous functions are two different function objects, off('click', function () {...}). Cannot remove the first anonymous function that has been bound.

   to achieve the removal effect, you can use off('click ') to remove all the handlers of the bound click event at one time.

   similarly, call off() without parameters to remove all types of event handling functions that have been bound at one time.

  • Event trigger condition

  one thing to note is that events are always triggered by user actions. For example, we monitor text box content changes:

	var input = $('#test-input');
	input.change(function () {

  when the user enters in the text box, the change event will be triggered. However, if you use JavaScript code to change the value of the text box, the change event will not be triggered:

	var input = $('#test-input');
	input.val('change it!'); // Unable to trigger the change event

   sometimes, we want to trigger the change event with code. We can directly call the change() method without parameters to trigger the event:

	var input = $('#test-input');
	input.val('change it!');
	input.change(); // Trigger change event

  input.change() is equivalent to input Trigger ('change '), which is short for trigger() method.

  • Browser security restrictions

  in the browser, some JavaScript code can be executed only when triggered by the user, for example, window Open() function:

// Unable to pop up a new window, it will be blocked by the browser:
$(function () {'/');

These "sensitive codes" can only be triggered by user actions:

	var button1 = $('#testPopupButton1');
	var button2 = $('#testPopupButton2');

	function popupTestWindow() {'/');
	} () {
	}); () {
    	// Do not execute popputtestwindow() immediately, and execute after 3 seconds:
    	setTimeout(popupTestWindow, 3000);

   when the user clicks button1, the click event is triggered. Since popputtestwindow() is executed in the click event handler function, which is allowed by the browser, the click event of button2 does not execute popputtestwindow() immediately, and the delayed popputtestwindow() will be intercepted by the browser.

4. Animation

Several animation styles built into jQuery:

  • show / hide

  calling show() and hide() directly without parameters will show and hide DOM elements. However, as long as a time parameter is passed in, it becomes an animation:

var div = $('#test-show-hide');
div.hide(3000); // Gradually disappear within 3 seconds

The time is in milliseconds, but it can also be 'slow' and 'fast' strings:

var div = $('#test-show-hide');'slow'); // Gradually display within 0.6 seconds

The toggle() method determines whether to show() or hide() according to the current state.

  • slideUp / slideDown

  show() and hide() expand or contract gradually from the upper left corner, while slideUp() and slideDown() expand or contract gradually in the vertical direction.

   slideUp() puts away a visible DOM element. The effect is like closing the curtain. slideDown() is the opposite, while slideToggle() determines the next action according to whether the element is visible:

var div = $('#test-slide');
div.slideUp(3000); // Gradually disappear upward within 3 seconds
  • fadeIn / fadeOut

The animation effect of   fadeIn() and fadeOut() is fade in and fade out, which is realized by continuously setting the opacity attribute of DOM element, while fadeToggle() determines the next action according to whether the element is visible:

var div = $('#test-fade');
div.fadeOut('slow'); // Fade out in 0.6 seconds
  • Custom animation

   if the above animation effect can't meet your requirements, then offer the last big move: animate(), which can realize any animation effect. The parameters we need to pass in are the final CSS state and time of DOM element. jQuery will constantly adjust the CSS within the time period until it reaches the value we set:

	var div = $('#test-animate');
    	opacity: 0.25,
    	width: '256px',
    	height: '256px'
	}, 3000); // CSS transitions to the set value within 3 seconds

animate() can also pass in another function, which will be called when the animation ends:

	var div = $('#test-animate');
    	opacity: 0.25,
    	width: '256px',
    	height: '256px'
	}, 3000, function () {
    	console.log('The animation has ended');
    	// Return to initial state:
    	$(this).css('opacity', '1.0').css('width', '128px').css('height', '128px');

In fact, this callback function parameter is also applicable to basic animation.

  • Serial animation

   the animation effect of jQuery can also be executed serially, and the pause can be realized through the delay() method. In this way, we can realize more complex animation effects, but the code is quite simple:

	var div = $('#test-animates');
	// Animation effect: slideDown - pause - zoom in - pause - zoom out
       	width: '256px',
       	height: '256px'
   	}, 2000)
      	 width: '128px',
       	height: '128px'
   	}, 2000);

   because the animation needs to be executed for a period of time, jQuery must constantly return new Promise objects to perform subsequent operations. Simply encapsulating animation in functions is not enough.

5. Expand

   when using the method of jQuery object, it is very convenient to use because jQuery object can operate a set of DOM and supports chain operation.

  but the built-in method of jQuery can never meet all the requirements. For example, we want to highlight some DOM elements, which can be realized by jQuery:

$('span.hl').css('backgroundColor', '#fffceb').css('color', '#d85030');

$('p a.hl').css('backgroundColor', '#fffceb').css('color', '#d85030');

   it's not good to always write duplicate code. In case it's more troublesome to modify the font in the future, can we unify and write a highlight() method?


$('p a.hl').highlight();

  the answer is yes. We can extend jQuery to implement custom methods. If you want to modify the highlighted logic in the future, you only need to modify one extension code. This approach is also known as writing jQuery plug-ins.

  • Writing jQuery plug-ins

A new way to bind jQuery objects is by extending $ fn object implementation. Let's write the first extension, highlight1():

	$.fn.highlight1 = function () {
    	// this is bound as the current jQuery object:
    	this.css('backgroundColor', '#fffceb').css('color', '#d85030');
    	return this;

   note that this inside the function is bound as a jQuery object when calling, so the internal code of the function can call the methods of all jQuery objects normally.

For the following HTML structure:

<!-- HTML structure -->
<div id="test-highlight1">
    <p>What is?<span>jQuery</span></p>
    <p><span>jQuery</span>It is the most popular one at present<span>JavaScript</span>Library.</p>

  you may have found it. Why did you return this; in the end;? Because jQuery objects support chained operations, the extension methods we write should be able to continue chained:


  otherwise, when the user calls, he has to split the above code into two lines.

  but this version is not perfect. Some users want the highlighted color to be specified by themselves. What should I do?

   we can add a parameter to the method and let the user pass in the parameter with an object. So we have a second version of highlight2():

	$.fn.highlight2 = function (options) {
    	// Various situations should be considered:
    	// options is undefined
    	// options has only some key s
    	var bgcolor = options && options.backgroundColor || '#fffceb';
    	var color = options && options.color || '#d85030';
    	this.css('backgroundColor', bgcolor).css('color', color);
    	return this;

For the following HTML structure:

<!-- HTML structure -->
<div id="test-highlight2">
    <p>What is?<span>jQuery</span> <span>Plugin</span></p>
    <p>to write<span>jQuery</span> <span>Plugin</span>Can be used to extend<span>jQuery</span>The function of.</p>

   for the processing of default values, we use a simple & & and | short circuit operators, which can always get a valid value.

   another way is to use the helper method $. Provided by jQuery extend(target, obj1, obj2, ...), It combines the attributes of multiple object objects into the first target object. When encountering an attribute with the same name, it always uses the value of the later object, that is, the higher the priority is:

// Merge the default value and the options passed in by the user into the object {} and return:
var opts = $.extend({}, {
    backgroundColor: '#00a8e6',
    color: '#ffffff'
}, options);

   then the user put forward his opinion on highlight2(): each call needs to pass in custom settings. Can I set a default value and use the parameterless highlight2() for future calls?

In other words, the default value we set should allow users to modify it.

Where is the default value more appropriate? It's definitely not appropriate to put global variables. The best place is $ fn.highlight2 is the function object itself.

So the final version of highlight() was finally born:

	$.fn.highlight = function (options) {
    	// Merge defaults and user settings:
    	var opts = $.extend({}, $.fn.highlight.defaults, options);
    	this.css('backgroundColor', opts.backgroundColor).css('color', opts.color);
    	return this;

	// Set default value:
	$.fn.highlight.defaults = {
    	color: '#d85030',
    	backgroundColor: '#fff8de'

The user is finally satisfied this time. When using, users only need to set the default value once:

$.fn.highlight.defaults.color = '#fff';
$.fn.highlight.defaults.backgroundColor = '#000';

Then you can call highlight() very simply.

For the following HTML structure:

<!-- HTML structure -->
<div id="test-highlight">
    <p>How to write<span>jQuery</span> <span>Plugin</span></p>
    <p>to write<span>jQuery</span> <span>Plugin</span>,To set<span>Default value</span>,And allow users to modify<span>Default value</span>,Or passed in at runtime<span>Other values</span>. </p>

Finally, we come to the principle of writing a jQuery plug-in:

  1. Give $ fn binding function to realize the code logic of the plug-in;
  2. return this at the end of the plug-in function; To support chain call;
  3. The plug-in has a default value of $ fn.< pluginName>. On defaults;
  4. When calling, the user can pass in the set value to override the default value.

Extensions for specific elements

  we know that some methods of jQuery objects can only act on specific DOM elements. For example, the submit() method can only target form s. If the extension we write can only target certain types of DOM elements, how should we write it?

   remember that the selector of jQuery supports the filter() method to filter? We can use this method to realize the extension for specific elements.

Write the code called by the user first:

$('#main a').external();

Then write an external extension according to the above method:

	$.fn.external = function () {
    	// return the result returned by each() supports chain calls:
    	return this.filter('a').each(function () {
        	// Note: this of the callback function inside each() is bound to the DOM itself!
        	var a = $(this);
        	var url = a.attr('href');
        	if (url && (url.indexOf('http://')===0 || url.indexOf('https://')===0)) {
            	a.attr('href', '#0')
             	.append(' <i class="uk-icon-external-link"></i>')
             	.click(function () {
                	if(confirm('Are you sure you want to go' + url + '?')) {

For the following HTML structure:

<!-- HTML structure -->
<div id="test-external">
    <p>How to learn<a href="">jQuery</a>?</p>
    <p>First, you have to learn<a href="/wiki/1022910821149312">JavaScript</a>,And understand the basic<a href="">HTML</a>. </p>


   the function of extending jQuery object is very simple, but we should follow the principle of jQuery. The extension method written can support chain calls, have default values and filter specific elements, so that the extension method looks no different from the method of jQuery itself.

Note: part of the summary comes from the official website of Liao Xuefeng!

Topics: Java Javascript Front-end Back-end