Home  >  Article  >  Web Front-end  >  A concise tutorial on using jquery_jquery

A concise tutorial on using jquery_jquery

WBOY
WBOYOriginal
2016-05-16 16:56:571245browse

1. Select web page elements
The basic design and main usage of jQuery is to "select a web page element and then perform some operation on it". This is the fundamental feature that distinguishes it from other function libraries.
The first step in using jQuery is often to put a selection expression into the constructor jQuery() (abbreviated as $), and then get the selected element.

The selection expression can be a CSS selector:

Copy the code The code is as follows:

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

can also be a jQuery-specific expression:
Copy code The code is as follows:

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

2. Change the result set
If multiple elements are selected, jQuery provides filters to narrow the result set:
Copy code The code is as follows:

$('div').has('p'); //Select the div element containing the p element
$(' div').not('.myClass'); //Select div elements whose class is not equal to myClass
$('div').filter('.myClass'); //Select div elements whose class is equal to myClass
$('div').first(); //Select the 1st div element
$('div').eq(5); //Select the 6th div element

Sometimes, we need to start from the result set and move to nearby related elements. jQuery also provides moving methods on the DOM tree:
Copy code The code is as follows:

$('div').next('p'); //Select the first p element after the div element
$(' div').parent(); //Select the parent element of the div element
$('div').closest('form'); //Select the form parent element closest to the div
$(' div').children(); //Select all child elements of div
$('div').siblings(); //Select sibling elements of div

3. Chain Operation
After selecting a web page element, you can perform certain operations on it.
jQuery allows all operations to be connected together and written in the form of a chain, such as:
Copy code The code is as follows:

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

We can unpack it like this, that is The following is as follows:
Copy code The code is as follows:

$('div')//Find div element
.find('h3')//Select the h3 element
.eq(2)//Select the third h3 element
.html('Hello'); //Select it The content is changed to Hello

This is the most commendable and convenient feature of jQuery. Its principle is that each jQuery operation returns a jQuery object, so different operations can be connected together.

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

Copy code The code is as follows:

$('div')
.find('h3')
.eq(2)
.html('Hello')
.end()/ /Return to the step of selecting all h3 elements
.eq(0)//Select the first h3 element
.html('World'); //Change its content to World

4. Element operations: value acquisition and assignment
When operating web page elements, the most common requirement is to obtain their values ​​or assign values ​​to them.
jQuery uses the same function to complete value (getter) and assignment (setter). Whether to get a value or assign a value is determined by the parameters of the function.
$('h1').html(); //html() has no parameters, which means taking out the value of h1 $('h1').html('Hello'); //html() has the parameter Hello, Indicates assigning a value to h1
The common value and assignment functions are as follows:
Copy the code The code is as follows:

.html() Get or set html content
.text() Get or set text content
.attr() Get or set the value of an attribute
.width() Get or Set the width of an element
.height() Get or set the height of an element
.val() Get the value of a form element


It should be noted that if The result set contains multiple elements, so when assigning a value, all the elements will be assigned; when taking a value, only the value of the first element will be taken out (except for .text(), which takes out the text content of all elements) .
5. Element operation: move
If you want to move the selected element, there are two methods: one is to move the element directly, the other is to move other elements so that the target element Get where we want to be.

Suppose we select a div element and need to move it behind the p element.

The first method is to use .insertAfter() to move the div element behind the p element:

Copy the code The code is as follows :

$('div').insertAfter('p');

The second method is to use .after() to add the p element in front of the div element:

Copy code The code is as follows:
$('p').after('div');

On the surface, the effect of these two methods is the same, the only difference seems to be the different operating perspective. But in fact, they have a major difference, that is, the returned elements are different. 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.

Using this mode of operation, there are four pairs of

Copy the code The code is as follows:

.insertAfter() and .after(): Insert elements from behind outside existing elements
.insertBefore() and .before(): Insert elements from front outside existing elements
. appendTo() and .append(): insert elements from the back inside existing elements
.prependTo() and .prepend(): insert elements from the front inside existing elements

6. Element operations: copy, delete and create

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

To clear the content of an element (but not delete the element) use .empty().

The method of creating a new element is very simple, just pass the new element directly into the jQuery constructor:

Copy code The code is as follows:

$('
Hello

');
$('
new list item
');
$('ul').append('
list item
');


7. Utility methods
In addition to operating on selected elements, jQuery also provides some tool methods (utilities) that can be used directly without selecting the element.
If you understand the inheritance principle of Javascript language, then you can understand the essence of tool methods. It is a method defined on the jQuery constructor, that is, jQuery.method(), so it can be used directly. Those methods for operating elements are methods defined on the prototype object of the constructor, that is, jQuery.prototype.method(), so an instance must be generated (that is, the element is selected) before use. If you don't understand this difference, it's not a big problem. Just understand the tool method as a method that can be used directly like the native JavaScript function.

Commonly used tool methods include the following:

Copy code The code is as follows:

$.trim() removes spaces at both ends of the string.
$.each() traverses an array or object.
$.inArray() returns the index position of a value in the array. If the value is not in the array, -1 is returned.
$.grep() returns elements in the array that meet certain criteria.
$.extend() Merge multiple objects into the first object.
$.makeArray() Convert the object into an array.
$.type() determines the type of object (function object, date object, array object, regular object, etc.).
$.isArray() determines whether a parameter is an array.
$.isEmptyObject() determines whether an object is empty (does not contain any attributes).
$.isFunction() determines whether a parameter is a function.
$.isPlainObject() determines whether a parameter is an object created with "{}" or "new Object".
$.support() Determines whether the browser supports a certain feature.

8. Event operations
jQuery can bind events to web page elements. According to different events, run corresponding functions.
Copy code The code is as follows:

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

Currently, jQuery mainly supports the following events:
Copy code The code is as follows:

.blur() The form element loses focus.
.change() The value of the form element changes
.click() Mouse click
.dblclick() Mouse double-click
.focus() The form element gets focus
.focusin() The child element gains focus
.focusout() The child element loses focus
.hover() At the same time, specify handler functions for mouseenter and mouseleave events
.keydown() Press the keyboard (long key press, only one event is returned )
.keypress() Press the keyboard (press the key for a long time, multiple events will be returned)
.keyup() Release the keyboard
.load() The element is loaded
.mousedown() Press Mouse down
.mouseenter() Mouse enters (does not trigger when entering a child element)
.mouseleave() Mouse leaves (does not trigger when leaving a child element)
.mousemove() Mouse moves inside the element
. mouseout() Mouse leaves (triggers when leaving child elements)
.mouseover() Mouse enters (triggers when entering child elements)
.mouseup() Releases mouse
.ready() DOM loading completed
.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
.submit() The user submits the form
.toggle() Run multiple functions in sequence according to the number of mouse clicks
.unload() The user leaves the page

The above events are all convenient ways of .bind() inside jQuery. Use .bind() to control events more flexibly, such as binding the same function to multiple events:
Copy code Code As follows:

$('input').bind('click change', //Bind click and change events at the same time
function(){
alert('Hello') ;
}
);

If you only want the event to run once, you can use the .one() method.

Copy code The code is as follows:

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

.unbind() is used to unbind the event.
Copy code The code is as follows:

$('p').unbind('click' );

All event handling functions can accept an event object as a parameter, such as e in the following example:
Copy Code The code is as follows:

$("p").click(function(e){
alert(e.type); //"click "
});

This event object has some useful properties and methods:
Copy the code The code is as follows:

event.pageX When the event occurs, the horizontal distance between the mouse and the upper left corner of the webpage
event.pageY When the event occurs, the vertical distance between the mouse and the upper left corner of the webpage
event.type The type of event (such as click)
event.which Which key was pressed
event.data Bind the data on the event object, and then pass in the event handler function
event.target The web element targeted by the event
event.preventDefault() Block the default behavior of events (for example, clicking a link will automatically open a new page)
event.stopPropagation() stops events from bubbling up to upper elements

In the event processing function, you can use the this keyword to return the DOM element targeted by the event:

Copy code The code is as follows :

$('a').click(function(){
if ($(this).attr('href').match('evil')){// If it is confirmed to be a harmful link
e.preventDefault(); //Prevent opening
$(this).addClass('evil'); //Add harmful class
}
}) ;

There are two ways to automatically trigger an event. One is to use the event function directly, and the other is to use .trigger() or .triggerHandler().
Copy code The code is as follows:

$('a').click();
$('a').trigger('click');

9. Special Effects
jQuery allows objects to present certain special effects.

$('h1').show(); //Show an h1 title
Commonly used special effects are as follows:

Copy code The code is as follows:

.fadeIn() Fade in
.fadeOut() Fade out
.fadeTo() Adjust transparency
.hide() Hide element
.show() Display element
.slideDown() Expand downwards
.slideUp() Roll up
.slideToggle() Expand or roll up an element in sequence
.toggle() sequentially Show or hide an element

Except for .show() and .hide(), the default execution time of all other special effects is 400ms (milliseconds), but you can change this setting.
Copy code The code is as follows:

$('h1').fadeIn(300); // Fade in within 300 milliseconds
$('h1').fadeOut('slow'); // Fade out slowly

After the special effect ends, you can specify a function to be executed.

Copy code The code is as follows:

$('p').fadeOut(300, function (){$(this).remove(); });

More complex special effects can be customized with .animate().

Copy code The code is as follows:

$('div').animate(
{
left : " =50", // Keep moving right
opacity : 0.2 // Specify transparency
},
300, // Duration
function(){ alert(' done!'); }//Callback function
);

.stop() and .delay() are used to stop or delay the execution of special effects.
$.fx.off If set to true, all web page effects will be turned off.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn