In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "what is the application method of jQuery". In the daily operation, I believe that many people have doubts about what the application method of jQuery is. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts about "what is the application method of jQuery?" Next, please follow the editor to study!
As soon as I know jQuery
JQuery is the abbreviation of JavaScript Query. JQuery is a very good JavaScript library. Even when the MVVM framework is popular today, more than half of the web pages and applications use jQuery directly or indirectly. JQuery's design philosophy is "Write Less, Do More", that is, write less and do more! Using jQuery can greatly simplify our JS code, thus improving the efficiency of development.
There are now three major versions of jQuery, which are 1.x, 2.x, 3.x. You can download the version you need from the official jQuery website and import it into your project locally, or you can use CDN. When you download jQuery, there are usually two optional versions, one is the compressed version (does not include line breaks and spaces, smaller, more for actual project development), and the other is the uncompressed version (including line breaks and spaces, slightly larger, mostly for learning and testing).
In addition, starting with the second large version, jQuery abandoned support for IE6, 7, 8 in order to optimize the network response and make the syntax more concise, and since 2.1.0, the compressed version of the file no longer contains comments. For better compatibility, the version number of the jQuery file we use here is 1.12.4.
Two jQuery cores
1Dome $symbol
JQuery is actually a function object. In fact, jQuery refers to the function object through the global variable jQuery, the $symbol is an alias for the jQuery variable, and to write less, we usually use the $symbol to represent the object.
Window.jQuery = = window.$; / / true jQuery = = $; / / true typeof ($); / / 'function'
If you use other frameworks, or customize the $variable, you may conflict with the $symbol of jQuery.
JQuery.noConflict ()
Before programming with jQuery, you can solve this problem by first calling the noConflict () method to remove the $symbol from jQuery. But from then on, you can only use the variable jQuery to use all the functions of jQuery.
2, parameters
Core functions can receive three types of parameters, namely, function references, strings, and DOM objects.
A) receive a function
$(function () {/ / some code}); / / the complete spelling of this way should be: / / $(document) .ready (function () {some code})
This approach is similar to the window.DOMContentLoaded method of native JS, which triggers this event as soon as the HTML document is parsed and a DOM tree is generated. However, multiple such methods can exist at the same time in jQuery.
B) receive string
Var box1 = $('div'); / / receive the css selector string, take the corresponding DOM element in the DOM tree, and wrap it as a jQuery object var box2 = $(''); / / receive the HTML code snippet, you can create the corresponding DOM element and wrap it around the jQuery object
C) receive DOM elements
Var box = document.getElementById ('# box'); var jBox = $(box); / / jQuery obj
If the core function receives a DOM element, it wraps the DOM element as a jQuery object and returns.
The jQuery object is actually an array of classes that holds the acquired DOM elements. The properties and methods provided by jQuery can be accessed only through the jQuery object.
3, static method
JQuery provides some static methods, such as traversing arrays, removing spaces in strings, determining data types, etc., these methods are very practical before ES5, but after ES5, native JS has implemented this similar method, so it will not be explained in detail here, you can check the official documents if you are interested. JQuery encapsulates ajax-related operations as static methods, which will be covered later. All we're going to talk about here is the holdReady method.
$.holdReady (true); $(function () {/ / some code}); $.joldReady (false); / / parameter true, pause the execution of the ready method, parameter false, and resume the execution of the ready method
Three jQuery attributes and nodes
1, selector
Selector is the core function of jQuery. Most of the selectors supported by css are supported in jQuery.
$('p'); / / tag selector $('.class'); / / class selector $('# id'); / / id selector $('[type=text]'); / / attribute selector $('input [type = email]'); / / combination selector $(# id p); / / descendant selector $(# id p:first-child); / / filter selector / /.
The DOM elements obtained through the core function are wrapped as jQuery objects and stored as an array of classes. We can get one of these through the eq method, and we can also get the DOM object through the get method. one
Var divList = $('div'); / / get all div var domDiv = divList.get (0); / / get the first Dom element, if any, var jqDiv = divList.eq (0); / / get the first jq object, if any, var another = $(domDiv); / / convert the Dom element to a jq object
In addition, jQuery provides some ways to find elements through a hierarchy.
$('div'). Find (' span'); / find the span within div, which is equivalent to $('div span') $(' li'). First (); / / get the first $('li'). Last () in the matching element; / / get the last $(' div'). Next () in the matching element; / / get the set of all matching div's next sibling elements $('div'). Prev () / / get the collection of previous sibling elements of div that you want to match $('div'). Parent (); / / get the common parent element of matching div $(' div'). Children (); / / get the collection of child elements of div $('div'). Siblings (); / get the collection of sibling elements of div / /.
2, attribute operation
After getting the DOM elements, jQuery wraps them into jq objects, and then you can modify the corresponding DOM elements, including CSS, text, attribute nodes, HTML structures, and so on, through the methods provided by jQuery.
Attributes are related to attribute nodes:
$('div'). Attr (' name','test'); / / set property name: name, attribute value: test $('div'). Attr (' name'); / / get the value of attribute name $('div'). RemoveAttr (' name'); / / delete attribute name * * $('div'). Prop (' name','test') The use of $('div'). Prop (' name'); $('div'). RemoveProp (' name'); / / prop is exactly the same as attr, except that prop can manipulate both the attribute of the DOM element and its attribute node
When the property is not displayed, getting it through the attr () method will return undefined, while the prop () method can return true or false, so if you want to retrieve and change the DOM attribute, such as the element's checked,selected, or disabled state, it is recommended to use the prop () method, other times use the attr method.
Note that when you use the appellate method to get the attribute value, only the corresponding property value of the first matching DOM element is returned. However, it is set to add this attribute to all matching DOM elements.
Related to the class class:
$('div') .addClass (' test'); / / add classes, if you need to add multiple classes, use spaces to separate $('div'). RemoveClass (' test'); / / delete classes, if you need to delete multiple classes, you can also use spaces to separate classes, you can also use spaces to separate $('div') .toggleClass (' test'); / / switch classes, if the DOM element already has this class, then delete it, if not, add it
Text and structure related:
$('div') .html (); / / get the content of the first matching div $(' div') .html ('
I am the paragraph.
'); / / set the content of all matched div $(' div'). Text (); / / get the text content of all matching elements $('div'). Text (' hello'); / / set the text content of all matched div $('input'). Val (); / / get the value of matching elements $(' input'). Val ('hello'); / / get the value of matching elements
Css related:
$('div') .css (' background-color','red'); / / set a single css attribute of the element $('div') .css ({width:'200px', height:'200px', background-color:'red'}); / / set multiple css properties through the object
Size and location related:
$('div') .width (); / / get the content area width of the div. You can set $(' div') .height () by passing parameters; / / get the content area height of the div, and pass the parameter / / innerWidth,innerHeight to indicate the width and height of the content+padding. / / outerWidth,outerHeight represents the width and height of the content+padding+border $('div') .offset () / / gets the offset of div from the viewport. The return value is an object $('div') .position () that contains top and left attributes and the value is numeric. / / gets the offset of div from the parent element. The return value is an object / / offset and position that contains top and left attributes and is numeric, and only works on visible elements.
3, node
JQuery also provides methods for adding, deleting, modifying and checking nodes.
("div") .append ("
Hello
Insert the element $("div") .prepend (") at the end of the div.
Hello
Insert the element $("div") .after ("inside") at the beginning of the div
Hello
"); / / insert element $(" div ") immediately after div. Before ("
Hello
"); / / insert the element $(" div ") .remove () immediately before the div; / / delete the div element, but leave the text $(" div ") .empty (); / / clear all the contents of the div
Four jQuery events
1, event binding and removal
JQuery provides two ways to bind events, the first is the specific event method of the on+ event name, and the second is to use the on method directly.
$('div') .onclick (function () {}); $(' div') .onclick ('click',function () {}); / / event handlers can be anonymous functions or function references. If unbinding events are involved, it is recommended to use function references.
JQuery's event binding is similar to the native JS's addEventListener method, which can bind multiple events of the same type at the same time without overriding each other.
JQuery unbinds the event through the off method.
Function test () {}; $('div'). On (' click',test); $('div'). Off (); / / remove all events bound by div $(' div'). Off ('click'); / / remove all click events bound by div $(' div'). Off ('click',test); / / remove specific events bound by div
2. Prevent event bubbling and default behavior
Using jQuery to prevent event bubbling and default behavior is the same as native JS. For those who are not clear, you can check out my "DOM event (1)".
$('div') .on (' click',function () {/ / some code e.stopPropagation ();}); / / prevent events from bubbling $('a') .on ('click',function () {/ / some code return false;// simple mode / / e.preventDefault (); / / W3C standard mode}); / / block default behavior
3, one-time events and automatically triggered events
Usually the event handlers that we bind to the element need specific events to trigger, such as click,mouseover, etc. JQuery provides the triggerHandler method, which allows you to manually trigger the event handler bound to the element without waiting for a specific event to occur.
$('div') .on (' click',function () {/ / some code}); / / generally wait until the user clicks div before the function is executed $('div') .triggerHandler (' click'); / / automatically triggers the click event of div without waiting for the user to click
JQuery also provides another method: trigger. Its function is the same as the triggerHandler method. The difference between them is that triggerHandler does not trigger the default behavior and bubbling of events.
$('div') .one (' click',function () {/ / some code}); / / jQuery binds an event handler that will only be triggered once through the one method
4, event delegation
JQuery implements the event delegate through the delegate method. There are some differences between the use of this method and the native JS, and the native JS implementation event delegate should also be moved to "events of DOM (1)".
$("ul") .delegate ("li", "click", function () {$(this) .toggleClass ("test");}); / / delegate the click event of li to ul, and the delegated element is usually the parent element of the delegated element
Five jQuery animation
1, show and hide
JQuery uses show method and hide method to show and hide elements. It works by modifying the display, width, height, and opacity properties of the element.
$('div') .show (1000); / / make div show that 1000 represents the duration of the entire process in ms $(' div') .hide (1000); / / hide div
These two methods can also accept a callback function as a second parameter to set the action to be performed after the animation is complete.
2, unfold and put away
JQuery gently expands and collapses elements through slideDown,slideUp. This method displays the element dynamically by changing the height (increasing or decreasing downward), and optionally triggers a callback function after the display is completed.
$("p") .slideDown (1000); / / expand, you can set a time to represent the duration of the whole process, in ms $("p") .slideUp (1000); / / put away $("p") .slideToggle (1000); / / switch
Unfold and put away the animation is often used to make a drop-down menu.
3, fade in and out
JQuery uses fadeIn and fadeOut to achieve fade in and out effect. The principle of this method is to modify the opacity attribute of the element without changing the width and height of the element. You can also receive a callback function.
$("div") .fadeIn (1000); / / fade in to receive a number as a parameter, indicating the duration of the process, in ms $("div") .fadeOut (1000); / / fade out $("div") .fadeTo (1000L0.5); / / adjust to the specified value of $("div") .fadeToggle (1000); / / switch
4, custom animation
JQuery uses the animate method to achieve custom animation effects.
$('div') .animate ({width:500px, opacity:0.8}, 1000); / / this method receives an object that represents the state of the element at the end of the animation, the second parameter is a number, indicating the duration, in ms, or you can receive a callback function as the third parameter
Note that the animation of jQuery is in the form of a queue, and each time an animation is written, one is inserted into the animation queue, and the latter can only be executed after the previous execution.
5, stop and delay
The stop method of jQuery can pause the animation in progress.
$('div') .stop (); / / stop the current animation immediately and start executing subsequent animations in the queue directly, if any, $(' div') .stop (true,true); / / the stop method can take two blloean values as parameters. The first specifies whether to clear other animations in the queue while stopping the current animation, and the second specifies whether to directly complete the other animations in the queue while stopping the current animation.
Since jQuery controls animation execution through queues, we recommend that you call the stop method before calling jQuery animation to avoid animation confusion.
$('div'). Stop (); $(' div'). Animate ({/ / some code}, 1000)
JQuery delays the execution of the animation through delay.
('div') .animate ({
Width:200px
Height:200px
}, 1000) .delay (1000). Animate ({
Background-color:red
}, 1000)
/ / wait for 1000ms to change the background color after changing the width and height
Six jQuery Ajax
JQuery encapsulates a full-featured Ajax method, and we have three commonly used jQuery methods, namely, $.ajax (), $.get (), and $.post ().
1Magneajax () method
The ajax method takes an object as a parameter, the object's property name is the setting parameter of ajax, and the property value is the set value of ajax.
$.ajax ({type: "POST", url: "some.php", data: "name=ren&age=12", cache: false; dataType: "text", success: function (msg) {/ / some code}, error:function (msg) {/ / some code})
The commonly used parameters are:
Type: request type. Available values are post and get.
Url: the address from which the request was sent.
Data: data sent to the server. Must be in the form of "key0=value0&key1=value1" or key-value pair (object).
Cache: specifies whether to read the cached data. True means to read, and false means not to read, and gets it directly from the server.
DataType: the type of data expected to be returned by the server. The optional value is xml,html,script,json,text.
The success:ajax request calls back the function successfully.
Error:ajax request failed callback function.
When using the ajax () method, all the setting parameters are optional, and there are many other parameters to choose from in addition to the appeal parameters, which gives us more flexibility when implementing ajax through jQuery. If you want to know more about the parameters, please check the official website of jQuery.
2 get () method
If you think the ajax () method is still too troublesome to send a simple get request, you can use the $. Get () method directly.
Get ("url", {name: "ren", age: "12"}, function (msg) {/ / some code}, "text")
This method requires only four parameters, the url of the request, the data sent, the callback function of the successful request, and the expected return value type.
3Perfect post () method
Using the $. Post () method is the same as $. Get (), they only need four parameters.
Post ("url", {name: "ren", age: "12"}, function (msg) {/ / some code}, "text")
4Jet load () method
The load () method can directly request the server's data and add it to the DOM element. Get mode is used by default, and if you send data to the server, it will be automatically converted to post mode.
$("div") .load ("test.html", {name: "ren", age: "12"}, function () {/ / some code}); / / loads a new html document into div and sends data to the server.
The load () method can take three parameters, the url of the request, the data sent to the server, and the callback function after the request is successful.
At this point, the study on "what is the application method of jQuery" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.