1. Select web elements

The basic design idea and usage of jQuery is to “select a web element and do something with it”. This is the fundamental feature that sets it apart from other Javascript libraries.

The first step in using jQuery is often to put a selection expression into the constructor jQuery() ($for short) and get the selected element.

Select expressions can be CSS selectors:

$(document) // Select the entire document object$('#myId') // Select the page element with ID myId$('div.myClass') // Select the div element whose class is myClass$('input[name=first]') // Select the input element whose name attribute is equal to first
Copy the code

It can also be a jquery-specific expression:

$('a:first') // Select the first a element in the page$('tr:odd') // Select the odd rows of the table$('#myForm :input') // Select the input element in the form$('div:visible') // Select the visible div element$('div:gt(2)') // Select all div elements except the first three$('div:animated') // Select the div element that is currently animated
Copy the code

Change the result set

The second design idea of jQuery is to provide a variety of powerful filters to filter the result set and narrow the selection.

    $('div').has('p'); // Select the div element that contains the p element$('div').not('.myClass'); // Select the div element whose class is not equal to myClass$('div').filter('.myClass'); // Select the div element whose class equals myClass$('div').first(); // Select the first div element$('div').eq(5); // Select the sixth div element
Copy the code

Sometimes we need to start from a result set and move to a nearby related element. JQuery also provides a way to move around the DOM tree:

$('div').next('p'); // Select the first p element after the div element$('div').parent(); // Select the parent of the div element$('div').closest('form'); // Select the form parent element nearest the div$('div').children(); // Select all the children of div$('div').siblings(); // Select the sibling element of div
Copy the code

Three, chain operation

The third design idea of jQuery is that when you finally select a web element, you can perform a series of operations on it. All operations can be linked together in a chain form, such as:

$('div').find('h3').eq(2).html('Hello');
Copy the code

Broken down, it looks like this:

$('div') // Find the div element.find('h3') // Select the h3 element.eq(2) // Select the third h3 element.html('Hello'); // Change its content to Hello
Copy the code

  

This is the most flattering and convenient feature of jQuery. It works because each step of the jQuery operation returns a jQuery object, so different operations can be linked together.

JQuery also provides the.end() method, which allows the result set to take a step back:

$('div'). Find ('h3'). Eq. (2). The HTML ('Hello'). The end ()// Go back to the step where all h3 elements are selected.eq(0) // Select the first h3 element.html('World'); // Change its content to World
Copy the code

Operations on elements: value and assignment

The most common requirement for manipulating web elements is to get their values or assign them to them.

The fourth design idea of jQuery is to use the same function to complete the getter and setter, i.e. “valuer” and “assignment” in one. Whether to evaluate or assign depends on the parameters of the function.

$('h1').html(); // HTML () takes no arguments to fetch the value of h1$('h1').html('Hello'); // HTML () takes the argument Hello, which assigns h1
Copy the code

Common values and assignment functions are as follows:

.html() takes or sets the HTML content.text() Takes or sets the text content.attr() takes or sets the value of an attribute.width() Takes or sets the width of an element.height() Takes or sets the height of an element .val() retrieves the value of a form elementCopy the code

Note that if the result set contains more than one element, then all elements are assigned; Fetching only the value of the first element (except.text(), which fetches the text content of all elements).

Element operations: move

The fifth design idea of jQuery is to provide two sets of methods for manipulating the position of elements in a web page. One set of methods is to move the element directly, and the other set of methods is to move other elements so that the target element is where we want it to be.

Suppose we select a div element and need to move it after the P element.

The first method is to use.insertafter (), which moves the div element after the p element:

$('div').insertAfter($('p'));
Copy the code

The second way is to use.after(), which precedes the p element in the div:

$('p').after($('div'));
Copy the code

On the surface, the effect of the two methods is the same, the only difference seems to be the perspective of operation. But in fact, there is one big difference between them, and that is that they return different elements. The first method returns the div element, and the second method returns the P element. You can choose which method to use based on your needs.

There are four pairs of operation methods using this mode:

.insertafter () and.after() : inserts elements.insertbefore () and.before() : inserts elements.appendto () and.append() from the front outside the existing element. Inside the existing element, insert elements from behind. PrependTo () and. Prepend () : Inside the existing element, insert elements from the frontCopy the code

Operations on elements: copy, delete, and create

In addition to moving elements, jQuery provides several other important ways to manipulate elements.

Copy elements using.clone().

Remove elements using.remove() and.detach(). The difference between the two is that the former does not retain the event of the deleted element, while the latter is retained for use when re-inserting the document.

Empty the element (but not delete it) using.empty().

Creating a new element is as simple as passing it directly into the jQuery constructor:

$('<p>Hello</p>'); $('<li class="new">new list item</li>'); $('ul').append('<li>list item</li>');
Copy the code

7. Tools and methods

In addition to operating on selected elements, jQuery also provides some element-independent utility methods. You can use these methods directly without having to select the element.

If you understand the inheritance principles of the Javascript language, you can understand the nature of the tool approach. It is a method defined on the jQuery constructor, jquery.method (), so it can be used directly. The methods that operate on elements are those defined on the constructor’s prototype object, jquery.prototype.method (), so you have to generate instances (that is, select elements) to use. If you don’t understand this distinction, it’s ok to think of utility methods as methods that can be used directly, like javascript native functions.

The following tools are commonly used:

$.trim() removes Spaces at both ends of the string. $.each() iterates over an array or object. $.inarray () returns the index position of a value in the array. If the value is not in the array, return -1. $.grep() returns the elements in the array that meet certain criteria. $.extend() merges multiple objects into the first object. $.makeArray() converts an object to an array. $.type() determines the class of objects (function objects, date objects, array objects, re objects, and so on). $.isarray () checks whether a parameter is an array. $.isemptyObject () determines whether an object is empty (without any attributes). $.isfunction () checks whether an argument is a function. $.isplainObject () determines whether a parameter is valid"{}"or"new Object"Object created. $.support() Checks whether the browser supports a feature.Copy the code

8. Event operation

The seventh design idea of jQuery is to tie events directly to web elements.

$('p').click(function(){ alert('Hello'); });Copy the code

Currently, jQuery supports the following events:

.blur() Form elements lose focus. .change() the value of the form element changes.click() mouse click.dblclick() mouse double-click.focus() the form element gets focus.focusin() child gets focus.focusout() child loses focus .hover() specifies a handler for both mouseenter and mouseleave events. Keydown () presses the keyboard (long button, returns only one event). Keypress () presses the keyboard (long button, returns only one event). Will return multiple events).keyup() release the key.load () element is loaded. Mousedown () press the mouse. Mouseenter () mouse entry (entering child elements does not trigger).mouseleave() Mouse away (leaving child element does not trigger). Mousemove () mouse moves inside the element. Mouseout () Mouse away (leaving child element also triggers) Resize () The size of the browser window changes. Scroll () the position of the scroll bar changes. Select () The user selects the content in the text box .toggle() runs multiple functions in sequence based on the number of mouse clicks. Unload () The user leaves the pageCopy the code

All of these events are handy ways to.bind() within jQuery. Use.bind() for more flexible control of events, such as binding the same function to multiple events:

$('input').bind('click change'.// Bind both the click and change events

    function() { alert('Hello'); });Copy the code

Sometimes, you only want the event to run once, using the.one() method.

$("p").one("click".function() { alert("Hello"); // Only run once, subsequent clicks will not run});Copy the code

.unbind() is used to unbind events.

$(‘p’).unbind(‘click’);

All event handlers can take an event object as an argument, such as e in the following example:

$("p").click(function(e) {alert (e. ype);// "click"});Copy the code

This event object has some useful properties and methods:

When the event. PageX event occurs, the horizontal distance between the mouse and the upper left corner of the page Event. type Type of the event (such as click) Event. which Which key is pressed Event. data Binds data to the event object, It then passes the event handler event.target to the web element event.preventDefault() to prevent the event's default behavior (such as clicking on a link, A new page will automatically open.) Event.stopPropagation () Stops events bubbling to upper elementsCopy the code

In event handlers, we can use the this keyword to return the DOM element for which the event was intended:

$('a').click(function(e) {if ($(this).attr('href').match('evil')) { // If confirmed as harmful linke.preventDefault();// prevents opening$(this).addClass('evil'); // add the harmful class}});Copy the code

There are two ways to trigger an event automatically. Either you use event functions directly, or you use.trigger() or.triggerHandler().

$('a').click(); $('a').trigger('click');
Copy the code

Special effects

Finally, jQuery allows objects to render certain special effects.

$(‘h1’).show(); // Display an H1 header

Common special effects are as follows:

FadeIn () fades in. FadeOut () fades out. FadeTo () adjusts transparency. Hide () hides elements. Show () displays elements. SlideDown () expands down .slidetoggle () unfolds or rolls up an element in turn. Toggle() displays or hides an element in turnCopy the code

The default execution time for all effects except.show() and.hide() is 400ms (ms), but you can change this setting.

$('h1').fadeIn(300); // Fades in 300 milliseconds$('h1').fadeOut('slow'); // Slowly fade out
Copy the code

After the effects are over, you can specify a function to be executed.

$('p').fadeOut(300.function() {$(this).remove(); });
Copy the code

More complex effects can be customized using.animate().

$('div'). The animate ({left : "50 + =".// Keep moving to the right

      opacity : 0.25 // Specify transparency},300.// The duration

    function() { alert('done! '); } // The callback function); .stop() and.delay() are used to stop or delay the effect. $.fx.off If set totrue, turn off all web effects.Copy the code