JQuery learning notes

  Front end, javascript, jquery

JQuery learning notes

Most of jQuery’s functions need to work according to the DOM model of the document. First, it needs to correctly parse the DOM model structure of the entire document. Using jQuery requires the entire document to be fully loaded by the browser before it can be started.

$(document).ready(function () {
    alert("Hello World!");
    $("p").click(function (event) {
        alert("Thanks for visiting!");
    })
});

$Is the variable name used in jQuery and can be usedjQuery.noConflict()To avoid conflicts, its return value is jQuery object.

jQuery.noConflict();
$j = jQuery.noConflict();

Transformation between jQuery Object and DOM Object

Use$()The result is a jQuery object. It encapsulates the operations of many DOM objects, but it is different from DOM objects. Only whenobjIs a DOM objectobj.innerHTML; Correspondingly, if it is a jQuery object, you should useobj.html().

  • From DOM object to jQuery object:$(obj)
  • From jQuery object to DOM object:obj[0]

The relatively normal conversion from jQuery object to DOM uses jQuery objectget()Methods:

$(function () {
    $("li").get();
    $("li").get(0);
    $("li").get(-1);
});

JQuery selector

1. General selector

  • $("*")Select all nodes
  • $("#id")ID selector, pay attention to some special characters, such as.
  • $(".class")Class selector
  • $("tag")label selector
  • $ ("child element")
  • $ ("Direct Child Element")
  • :focusGet focus element
  • :first-child/:last-childSelect the first/last element
  • :first/:lastIntercept the first/last eligible element
  • ("pre+next")Direct sibling element
  • ("pre~siblings")Brother element
  • :nth-child()Index selection, index starts from 1

    • :nth-child(odd)
    • :nth-child(even)
    • :nth-child(4n)

2. Attribute selector

  • [name~="value"]The attribute includes a word
  • [name="value"]The property is exactly equal to the specified value
  • [name! ="value"]The property is not equal to the specified value
  • [name]Includes elements with specified attributes

3. Control Selector

  • :checkedSelect all selected elements
  • :selectedSelected element
  • :disabled/:enabledSelect disabled/not disabled elements
  • :hiddenHidden elements are not only[type="hidden"], anddispla:none
  • :visibleVisible controls,visibility:hiddenAndopacity:0Also considered visible
  • :input :button :checkbox :file :image :password :radio :reset :submit :textSpecific controls, image controls are[type="image"]

4. Other selectors

  • [name="value"] [name2="value2"]Multiple AND conditions
  • ("selector1, selector2, selectorN")Multiple OR conditions
  • :not()Negative choice
  • (':contains("text")')The element that contains the specified content
  • :eq() :lt() :gt() :even :oddList index selection (negative numbers are not supported)
  • (':has(selector)')Eligible re-filtration
  • :headerchooseh1,h2,h3 ...Title element
  • :only-childAn element with only one child element
  • :emptyEmpty element, i.e. no content or element
  • :parentNon-empty element

Node roaming

1. Call chain processing

  • .add()Adds a new object to an existing node sequence
  • .andSelf()In the call chain, the original sequence is added at any time.
  • .eq()Specifies the index selection node and supports negative numbers
  • .filter() .is() .not() .find() .first() .last() .has()Sequence selection
  • .end()Node backtracking
$(function () {
    $('ul.first').find('.foo').css('background-color', 'red')
        .end().find('.bar').css('background-color', 'green');
});

2. Child nodes

  • .children()For all child nodes, filter conditions can be added..children(selector)

3. Brother node

  • .siblings() .next() .nextAll() .nextUntil() .prevAll() .prevUntil() .closet()Select sibling node

4. Parent node

  • .parent() .parents() .parentUntil()Parent node selection

Element control

1.attributesAndpropertiesThe difference between

  • attributesIs an attribute node in an XML structure

    • <div onload="prettyPrint()"></div>
  • propertiesIs a DOM object, an object attribute

    • $('body').get(0).tagName;

2. Class and Attribute Control

  • .addCLass() .hasClass() .removeClass()Add a class, judge whether there is a specified class, delete the class
$('body').addClass('test');
$('body').addClass(function (index, current) {
    return current + 'new';
});
$('body').removeClass('test');
$('body').removeClass(function (index, current) {
    return current + ' ' + 'other';
});
  • .toggleClass()Class to switch
$('img').toggleClass(); //对所有类的开关
$('img').toggleClass('test'); //对指定类的开关
$('img').toggleClass(isTrue); //根据`isTrue`判断所有类的开关
$('img').toggleClass('test', isTrue); //根据`isTrue`判断指定类的开关

//同 `$('img').toggleClass('test');` 只是类名由函数返回
$('img').toggleClass(function (index, className, isTrue) {
    return 'name'
});

// `isTrue`作为函数的第三个参数传入
$('img').toggleClass(function (index, className, isTrue) {
    return 'name'
}, isTrue);
  • .attr()Gets or sets an attribute value
// $("#greatphoto").attr('alt'); //获取属性`
$("#greatphoto").attr('alt', 'Shenzhen Brush Seller'); //设置属性`

// 同时设置多个属性
$('#greatphoto').attr({
    alt: 'Shen Brush Seller',
    title: 'photo by Kelly Clark'
});

//设置属性为函数返回值,函数的上下文为当前元素
$('#greatphoto').attr('title', function (i, val) {
    return val + ' - photo by Kelly Clark';
})
  • .prop()Same usage.attr()Only the object becomesproperties
  • .removeAttr() .removeProp()Delete attribute
  • .val()Sets or gets the form value of an element, usually used for form elements
$('input').val();
$('input').val('other');
  • .html()Sets or gets the node of the elementhtml
$('div').html();
$('div').html('<div>测试</div>');
$('div').html(function (index, old) {
    return old + '<span>另外的内容</span>';
});

3. Style control

  • .css()Gets or sets the specified CSS style
$('body').css('background-color', 'red');
$('body').css('background-color', function (index, value) {
    return value + '1';
});
$('body').css({color: 'green', 'background-color': 'red'});
  • .width() .height()Gets or sets the width and height of the element
$('body').width();
$('body').width(50);
$('body').width(function (index, value) {
    return value += 10;
})
  • .innerWidth() .innerHeight() .outerHeight() .outerWidth()Other dimension values for elements
  • .scrollLefgt() .scrollTop()Gets or sets the position of the scroll bar
  • .offset() .position()Gets the coordinates of the element

    • offsetIs relative todocument,positionIs relative to the parent element

Structural control

1. Text node

  • .html() .text()Sets and gets the text value of the node. When setting up.text()Escape the label when getting.text()All tags will be removed.

2. Child nodes

  • .append() .prepend()
$('.inner').append('<p>Test</p>');

Parameters can take many forms:

var $newdiv1 = $('<div id="object1"/>'),
    newdiv2 = document.createElement('div'),
    existingdiv1 = document.getElementById('foo');

$('body').append($newdiv1, [newdiv2, existingdiv1]);

3. Brother node

  • .after() .before()
$('.inner').after('<p>Test</p>');

4. Parent node

  • .wrap() .wrap() .wrapInner()
$('.inner').wrap('<div class="new"></div>');
$('.inner').wrapAll('<div class="new"></div>');
$('.inner').wrapInner('<div class="new"></div>');

5. Copy/Delete/Replace Nodes

  • .clone()Replication node, optional parameter indicating whether to process bound events and data

    • .clone(true)Handle the current node’s events and data
    • .clone(true, true)Handle events and data of current node and all child nodes
  • .detach()Temporarily remove the node and then restore the specified location again.
  • .remove()Permanently remove nodes
  • .empty()Clear all internal contents of a node
  • .unwrap()Remove the parent node of the node

Tool function

  • .map()Traverse all members
$(':checkbox').map(function () {
    return this.id;
}).get().join(',');

$(':checkbox').map(function (index, node) {
    return node.id;
}).get().join(',');
  • .slice()Sequence slice, supports one or two parameters, supports negative numbers
$('li').slice(2).css('background-color', 'red');
$('li').slice(2, 4).css('background-color', 'green');
$('li').slice(-2, -1).css('background-color', 'blue');

Universal tool

  • $.each() $.map()Traversing the list,$.map()Can be used for objects
$.each([52, 97], function (index, value) {
    console.log((index + ' : ' + value));
});
$.map([0, 1, 2], function (index, n) {
    return n + 4;
});
$.map([0, 1, 2], function (n) {
    return n > 0 ? n + 1 : null;
});
$.map([0, 1, 2], function (n) {
    return [n, n + 1];
});

var dimensions = {width: 10, height: 15, length: 20};
$.map(dimensions, function (value, key) {
    return value * 2;
});

var dimensions = {width: 10, height: 15, length: 20};
$.map(dimensions, function (value, key) {
    return key;
});
  • $.extend()Merging objects, the first parameter indicates whether to recursively drill down
var object = $.extend({}, object1, object2);
var object = $.extend(true, {}, object1, object2);
  • $.merge()Merge list
$.merge([0, 1, 2], [2, 3, 4]);
  • .grep()Filter the list, and the third parameter indicates whether it is inverted.
$.grep([0, 1, 2], function (array, index) {
    return n > 0;
});//[1,2]
$.grep([0, 1, 2], function (array, index) {
    return n > 0;
}, true);//[0]
  • $.inArray()Existence judgment
$.inArray(value, array [, fromIndex])
  • $.isArray() $.isEmptyObject() $.isFunction() $.iSNumeric() $.isPainObject() $.isWindow $.isXMLDoc()Type judgment
  • $.noop()Empty function
  • $.now()Current timestamp, value is(new Date).getTime()
  • $.parseJson() $.parseXML()Parses a string into an object
var xml = "<rss version='2.0'><channel><title>RSS Title</title></channel></rss>",
    xmlDoc = $.parseXML(xml),
    $xml = $(xmlDoc),
    $title = $xml.find("title");
  • $.trim()Head off, tail off$.trim(str)
  • $.type()Determine the type of parameter
  • $.unique()After traversing, the weight is removed.$.unique(arraty)

Context binding

  • $.proxy()Bind context for function

    • $.proxy(function,context)
    • $.proxy(context,name)
var o = {
    x: '123',
    f: function () {
        console.log(this.x)
    },
};
var go = function (f) {
    f()
};

o.f();// 123
go(o.f);// undefined
go($.proxy(o.f, o));//123
$.proxy(o, 'f')(); //123

When a function is passed, it loses its original context.

Store data in nodes

JQuery provides a mechanism to use nodes as containers for data storage.

  • $.data()Acquiring/Setting Data from Nodes
  • $.removeData()deleted data

On the internal implementation, jQuery will add an internal identifier to the specified node as followskeyTo store data in a structure of an internal closure.

In fact, jQuery’s event binding mechanism also uses this set of data interfaces.

$.data($('#data').get(0), 'test', '123');
$('#data').data('test', '456');

Event handling

1. Event binding

After jQuery1.7, unified usage is recommended.on()For event binding.

  • .on()Binding eventon()The basic usage of is:.on(event,handler)
  • .off()Remove event
  • .one()Bind single event
$('#btn').on('click', function (eventObj) {
    console.log('Hello');
})

Forhandler, whose default context is the node that triggered the event:

$('#btn').on('click', function (eventObj) {
    console.log(this);
})

Use$.proxy()You can freely control the context:

$('#btn').on('click',
    $.proxy(function (eventObj) {
        console.log(this.a);
    }, {a: 123})); // 123

eventParameters also support the adoption of:

- 以`.`分割的子名字
- 以空格分割的多个事件
$('#btn').on('click.my', (function (eventObj) {
            console.log('123');
        }
    )
);
var f = function () {
    $('#btn').off('click.my')
};

Multiple events:

$('#btn').on('click.my click.other',
    (function (eventObj) {
            console.log('123');
        }
    )
);
var f = function () {
    $('#btn').off('click.my')
}

on()Another form of call to:

$('#btn').on({
    'click': function (eventObj) {
        console.log('click');
    },
    'mousemove': function (eventObj) {
        console.log('move');
    }
});

off()How to use andon()Completely similar:

var f = function (eventObj) {
    console.log('Hello');
};
$('#btn').on('click', f);
$('#btn').off('click');

2. Event Trigger

There are two ways to trigger an event, one is to use a predetermined “event function” (.click(),.focus()), 2 it is to usetrigger()OrtriggerHandler().

$('#btn').on('click', function (eventObj) {
    console.log("hello");
});
$('#btn').click();
$('#btn').trigger('click');

trigger()AndtriggerHandler()The difference is that the trigger event precedes and the latter executes the binding function.

$('#btn').on('focus', function (event) {
    console.log("Hello");
});
$('#btn').triggerHandler('focus');

trigger()AndtriggerHandler()It is also used to trigger custom events.

$('#btn').on('my', function (event) {
    console.log("Hello");
});
$('#btn').triggerHandler('my');

trigger()AndtriggerHandler()When an event is triggered, parameters can be taken:

$('#btn').on('my', function (event) {
    console.log(obj);
});
$('#btn').trigger('my', {a: 123});

3. Event type

Behavioral events:

  • .click()Click
  • .dbclick()Double – click
  • .blur()When losing focus
  • .change()When the value changes
  • .focus()When getting the focus
  • .focusin()Get focus for jQuery extension
  • .focusout()The Lost Focus of jQuery Extension
  • .resize()Resize
  • .scroll()Rolling
  • .select()Be chosen
  • .submit()The form was submitted

Keyboard events:

  • .keydown()Press the key
  • .keyup()Release key

Mouse events:

  • .mousedown()Tap the mouse
  • .mouseup()Release the mouse
  • .mouseover()Cursor move in
  • .mouseout()Cursor move out
  • .mousemove()The cursor moves over it.
  • .mouseleave() .mouseenter()Cursor Move Out/In

Page events:

  • .ready()Ready
  • .unload()When leaving the current page, forwindowObject
  • .error()When an error occurs
  • .load()Loading

4. Event object

  • event.currentTarget,event,targetEvent Binding Node/Trigger Node of Event (Bubble Behavior)
  • event.delegateTargetThe object to which the event is bound is usuallyevent.currentTarget
  • event.relatedTargetRelated nodes are mainly used for some transformational events. For example, the mouse moves in to indicate which node it came from.
  • event.whichIndicates which button triggered the event, and the key identifiers of the mouse and keyboard are unified in this attribute.
  • event.preventDefault() event.isDefaultPrevented()Prohibit default behavior
  • event.stopImmediateProgation() event.isImmediateProgationStopped()Not only is bubbling forbidden. The continuation of the binding function chain is also terminated
  • event.stopPropagation(),event.isPropagationStopped()Bubbles are forbidden.
  • event.pageX,event.pageYRelative to when the event is triggereddocumentThe mouse position of
  • event.namespaceNamespace when the event is triggered, such astrigger('click.namespace')
  • event.dataAdditional incoming data
  • event.resultThe return value of the last binding function
  • event.timeStampThe time when the event is triggered, and its value is(new Date).getTime()
  • event.typeevent type

If a binding function finally returnsfalse, the default isevent.preventDefault()Andevent.stopPropagation()Behavior.

AJAX

1. Requests and callbacks

In jQuery’s AJAX, there is only one core request handler, which is$.ajax(), followed by a simple upper-level function.

$.ajax()The basic form of use of is:

jQuey.ajax(settings) settingsIs an object that contains all the configuration items.

  • urlThe address of the request.
  • typeThe requested method type,GET,POST. The default isGET.
  • dataData to send
  • dataTypeData type returned by server, supportedxml,html,script,json,jsonp,text
  • successThe handler to call when the request succeeds.success(data, textStatus, jqXHR)
  • contextContext of callback function execution
  • cacheThe default istrue, whether to add a random parameter to the request to prevent browser caching
  • errorThe calling function when the request is wrong.

    • error(jqXHR, textStatus, errorThrown)
    • The second parameter is a string representing the request status:timeout,error,abort,parsererror
    • The third parameter is the specific error description when an HTTP error occurs:Not Found,Internal Server ErrorWait
  • completeA callback function at the end of a request, whether successful or unsuccessful.

    • complete(jqXHR, textStatus)
    • The string representing the request status when the second parameter is:success,notmodified,error,timeout,abort,parsererror.
  • jsonpA parameter name, the default iscallback, commonly used to indicate the callback function name. set atfalseCan let the request have nocallbackParameters.
  • jsonpCallback callbackParameter value. The default is an automatically generated random value.

2. Status of the request

For all global AJAX requests, each event of any global AJAX request can be bound on any node:

$('#loading').ajaxStart(function () {
    $(this).show();
});
  • .ajaxStart()When the request is about to be issued
  • .ajaxSend()When the request is about to be issued (at.ajaxStart()After)
  • .ajaxSuccess()Request succeeded
  • .ajaxError()Request error
  • .ajaxComplete()Request completed
  • .ajaxStop()Request ends (at.ajaxComplete()After)

3. Tool function

  • .serialize()Parses a form parameter item and returns a string
$('form').submit(function () {
    alert($(this).serialize());
    return false;
});
  • .serializeArray()Parses form parameter items and returns a list object.
$('form').submit(function () {
    alert($(this).serializeArray());
    return false;
});

Generalization callback

1.Deferred

  • DeferredObject is the callback management object introduced in jQuery1.5. Its function is to put a bunch of functions into a calling chain in sequence, and then call these functions in sequence according to the state. All AJAX operations are encapsulated using it.
var obj = $.Deferred(function (a) {

});
obj.done(function () {
    console.log("1");
});
obj.done(function () {
    console.log("2");
});
obj.resolve();

In general: jQuery’sDeferredObjects have three states:done,fail,process.

- `process` 只能先于其他两个状态先被激发。
- `done`和`fail`互斥,只能激发一个。
- `process`可以被重复激发,而`done`和`fail`只能激发一次。

Then jQuery provides some functions for adding callbacks, firing states, etc.

  • deferred.done()Add one or more successful callbacks
  • deferred.fail()Add one or more failed callbacks
  • deferred.always()Add a function that applies to both success and failure
  • deferred.progress()Add a function to prepare the callback
  • deferred.then()Accept three functions in turn for success, failure and preparation
  • deferred.reject()Excitation failure state
  • deferred.resolve()Stimulate success status
  • deferred.notify()Excitation readiness

If oneDeferredHas been fired, the newly added corresponding function will be executed immediately.

JQuery also provides ajQuery.when()The callback management function of can be used to conveniently manage the concurrency of multiple events.

var defer = $.ajax({
    url: 'test.html',
    dataType: 'json'
});
defer.done(function (data) {
    console.log(data);
});

done()Do and usesuccess()The definition is the same.

Use when we need to complete requirements such as “execute functions when both request a and request b are complete.”$.when()Just do it.

var defer_1 = $.ajax({
    url: 'json.html',
    dataType: 'json'
});
var defer_2 = $.ajax({
    url: 'jsonp.html',
    dataType: 'jsonp'
});
var new_defer = $.when(defer_1, defer_2);
new_defer.done(function () {
    console.log("hello");
});

In$.when()hit the targetDeferred, as long as there is one isfail, the overall result isfail.

DeferredThe order of execution of the callback functions of is the same as the order of their addition.

A special note here is thatdone/fail/alwaysAndthenThe difference between the return values of. Functionally, they can all add callback functions, but the return values of methods are different. The return value of the previous group is the original onedeferObject, andthenThe return is a new onedeferObject.

thenReturn to the newdeferThis form can be used to conveniently realize the chain call of asynchronous functions.

defer.done(function () {
    return $.ajax({
        url: '/json',
        dataType: 'json',
        success: function () {
            console.log("inner");
        }
    })
}).done(function () {
    console.log("hello");
});

It is equivalent to calling twice.defer.done,defer.doneAfter the two registered callback functions are executed in turn, the output you see is:hello,inner.

This is twicedefer.doneAs a result, the first callback function returned a newdeferIt doesn’t work.

If it were replaced bythenMethods:defer.then(function () {...});

It follows twicedefer.doneIt’s different.new_deferWill be ininnerFrom theredeferWhen triggered, it will be triggered again, so the output result is:inner,hello.

More generallythenThe behavior of, is the return value of the previous registration function, will be used as the parameter value of the later registration function:

var defer = $.ajax({
    url: '/json',
    dataType: 'json'
});
defer.then(function (res) {
    console.log(res);
    return 1;
}).then(function (res) {
    console.log(res);
    return 2;
}).then(function (res) {
    console.log(res);
});

The input result of the above code is:ajax response,1,2.

2. Callbacks

In fact,DeferredMechanism, only inCallbacksThe upper layer of the mechanism is simply encapsulated.CallbacksObject is the original callback management mechanism defined in jQuery.

var obj = $.Callbacks();
obj.add(function () {
    console.log("1");
});
obj.add(function () {
    console.log("2");
});
obj.fire();

CallbacksObject initialization supports a set of control parameters:

  • $.Callbacks(flags)Initializes a callback management object.flagsIs a number of strings separated by spaces to define the behavior of this callback object:

    • onceThe callback chain can only be fired once
    • memoryAfter the callback chain is fired, the newly added function is executed immediately
    • uniqueThe same callback function can only be added once.
    • stopOnFalseWhen a callback function returnsfalseTo terminate the execution of the call chain

CallbackSThe control method of:

  • callbacks.add()Add one or a string of callback functions
  • callbacks.fire()Trigger callback
  • callbacks.remove()Removes the specified function from the call chain
  • callbacks.empty()Empty call chain
  • callbacks.disable()Closes the continuation of the call chain and the newly added function will not be executed.
  • callbacks.lock()Lock the call chain, but if it is openedmemoryTheflag, the newly added function will still execute
  • callbacks.has()Check if a function is in the callback chain
  • callbacks.fired()Check if callback chain is fired
  • callbacks.locked()Check if callback chain is locked