[Turn from setting] magical jquery

Source: Internet
Author: User
Tags xpath

Objective

The previous project has always been in the use of jquery, encountered problems to turn over the API, has never been compared to the summary and collation of the system. Recently because to do a training, because the comparison system summed up the relevant knowledge of JavaScript, handy to make a note. When it comes to jquery, it's hard to avoid javascript, so I'm going to make a brief introduction to two articles, the first is jquery, and the second chapter is a more in-depth discussion of JavaScript.

The benefits of jquery

jquery is a lightweight JS framework, which in the period after the emergence of a considerable number of people to win the favor, it has a lot of advantages: concise code, easy to get started, browser-compatible, plug-in rich .... Wait a minute. Personally, I chose jquery to be fond of its simple, powerful selectors and fast, flexible event handling.

Okay, so much gossip, let's get to the point, before we introduce jquery, let's look at a piece of code:

View Code
<form id= "LoginForm" action= "/" method= "POST" >        <p> User name: <input type= "text" name= "UserID"/></ P>        <p> Secret  code: <input type= "password" name= "UserPassword"/></p>        <p> captcha:< Input type= "text" name= "Validatecode"/></p>        <p>            <input type= "Submit" value= "Login"/>        </p>    </form>

In this code we define a login form that may exist everywhere on our site, and we generally need to do something before the form is submitted, such as form validation. However, I don't want to write a section of JS on each page that has such a form to validate the form, and jquery can help us solve the problem very concisely. Take a look at the following code:

View Code
<script type= "Text/javascript" >        $ (function () {            $ ("Form#loginform Input[type=submit]"). Click ( function () {                var validate = true;                $ ("Form#loginform"). Find ("Input[type=text],input[type=password]"). each (function () {                    if ($ (). val () = = "") {                        validate = false;                        Alert ("Incomplete login form completed");                        return false;                    }                });                return validate;            }    ); </script>

This code verifies that text and password are empty before each id= "loginform" form commits. Of course, you can not each form of the ID is "LoginForm" (although the form browser without this ID will not report JS errors), and not each form is submitted with submit, then to verify the submission of the form to do? This is hard to do with jquery, we can change the code above, the code is as follows:

View Code
<form action= "/" method= "POST" >        <p> User name: <input type= "text" empty= "false" Name= "UserID"/></p >        <p> Secret  code: <input type= "Password" empty= "false" Name= "UserPassword"/></p>        <p > captcha: <input type= "text" empty= "false" Name= "Validatecode"/></p>        <p>            <input type= " Submit "value=" Login "/>        </p>    </form>
View Code
<script type= "Text/javascript" >        $ (function () {            $ ("form"). Submit (function () {                var validate = true;< c3/>$ (This). Find ("Input[empty=false]"). each (function () {                    if ($ (). val () = = "") {                        validate = false;                        Alert ("Incomplete login form completed");                        return false;                    }                });                return validate;            }    ); </script>

As you can see, we have added a empty= "false" property to the element that the form needs to validate (some browsers support the required property, in order to illustrate that jquery supports custom attributes, empty is used), and then we do input validation before the form submission. Of course, you can also use other custom property names or values to distinguish between the objects you want to verify, such as inputtype= "email", inputtype= "phone" and so on to verify the mailbox or phone number, just need to make the form submission logic slightly modified. jquery has already let us enjoy the HTML5 features in advance.

OK, having said so much, have you had a little interest in jquery? So below, I briefly put jquery some common knowledge to do the collation and induction.

First, the constructor function

-1.jquery (selector, [context]) selector A string containing CSS selectors context a DOM element set, document, or JQuery object to be found. For example:
$ (". Navo")   //Find all class= "Navo" elements under current document $ (". Navo", "form")  //Find the elements of class= "Navo" in all the form under the current document
-2.jquery (Element) element one that is used to encapsulate the DOM elements into a JQuery object. For example:
$ (document.getElementById ("signin"));  Convert an object id= "Signin" to a jquery object
Mentioned here, incidentally, in the use of jquery, we are divided into window and jquery two kinds of objects, using the Window object can only use some properties and methods of the Window object, as well, jquery objects can only use jquery's methods and properties. Of course, the Window object and the JQuery object can be converted to each other.   -3.jquery (Elementarray) elementarray An array of DOM elements used to encapsulate the JQuery object. This is very similar to the second constructor, except that one is a single object and the other is an array of objects. For example:
$ (Document.getelementbyname ("signin"))  //Convert all Name= "signin" objects to jquery arrays
-4.jquery (jquery object) jquery object one used for cloning jquery objects.   The most common usage is: $ (this). For example:
$ ("input"). each (function () {if ($ (). val () = = "") {//you can do something}});
The HTML tag string 5.-jquery (HTML, [ownerdocument]) HTML is used to dynamically create DOM elements, not XML ownerdocument a new element of a document will be created. For example:
$ ("<div></div>");
6.-jquery (HTML, props) HTML a single-tagged HTML element string (for example: <div/> or <div>).  Props accesses the properties, events, and methods of the newly created element. For example:
$ ("<div/>", {class: "Test",   text: "Click me!",   click:function () {$ (this). Toggleclass ("tes        T "); }       });
7.-jquery (callback) callback when Dom finishes loading, this is a constructor that is often used, and the most common notation is: $ (function () {}); This is the same as: $ (document). Ready (  function () {}); For example:
$ (function () {  //you can do something  ... });
Well, the constructor is introduced here, and the selector is described below. Second, selectorThe-jquery selector supports IDs, tagName, css1-3 expressions, pseudo-classes, and wildcard characters. Since the version of jQuery1.3, XPath is no longer supported. And personally think XPath syntax format a bit of the pit dad, do not like. Let's look at some examples of jquery selectors:
-   $ ("#name")  //select id= "name" element $ ("div")//Select all div $ (". ClassName")  //Select all class= "ClassName" element $ ("ul> Li ")//Select all the next level Li elements of UL $ (" form input ")  //Select all input elements under form $ (" Input[type=checkbox] ")  //Select All checkboxes $ (" Form Input:text ")//Select all text elements
-jquery supports multiple attribute filters
$ ("input[name$=shop][type=text]");
-jquery support for selecting multiple elements
$ ("Div,span,p,.classname")
-jquery has a tool class that provides some find objects: Find (""),. Has (""),. EQ (0), "GT (0),: LT (5),. First (),. Last (),. First-child,. Last-child (),. Not ( ),. Next (),. Nextall () ... When using the property values returned by the jquery object, most of the JQuery object's property values are the same as the DOM object's property values, except for a subset of them, such as when Checkboxcheckbox renders the selected state: <input type= "checkbox" Checked= "Checked" value= ""/> Then we use jquery to get the selected checkbox with $ ("input:checked") can be obtained, to determine whether a checkbox is selected, if ($ ("# Checkboxobject "). attr (" checked ") ==true), jquery gets the checked attribute value of the selected checkbox to True, not" checked ". In addition, We are getting the value of an element group, we should iterate over each object and remove Value,jquery by default only returns the value of the first object. Instead of the request.form["name" in our ASP. NET, the values of all objects are separated by ",". Or take a checkbox for example:
function Getcheckboxvalue () {var value= "";  $ ("input:checked"). each (function () {Value + = $ (this). Val ();  }); return value; }
Using the jquery selector, we need to be aware of: 1.-gets the returned object as a JQuery object (collection Object) through the jquery selector, and cannot directly invoke the method defined by the DOM. 2.-jquery objects and Dom objects can be converted to each other. Ordinary DOM objects can generally be converted to jquery objects through $ (), and the JQuery object to be converted to a DOM object must take one of these items out of the index, which is usually indexed. Some of the following examples are correct:
$ (document.getElementById ("MSG")). html (); $ ("#msg"). html (); $ ("#msg") [0].innerhtml;$ ("#msg"). EQ (0) [0].innerhtml; $ ("#msg"). Get (0). InnerHTML;
Iii. Events -jquery has provided us with a variety of event handling methods, and we do not need to write events directly on HTML elements, but we can add events directly to the objects acquired through jquery. So we don't have to add various on* properties and define various global functions on the page element. This is a very happy thing for developers. In jquery, it is common practice for selectors to match events to complete a sequence of actions. The most common practice is: select.do (). Do () ..... So most of the events in jquery are adding events immediately after selecting an object. The semantics of jquery add Event are: $ ("element"). EventName (function () {}), of course, function is not required, if not write function, it represents the execution of the event. For example: $ ("input[type=submit]"). Click (); Indicates the Click event that executed the submit.  jquery commonly used events are: Click, DblClick, hover, load, blur, focus, change, select, serialize, Serializearray, submit ..... In addition to the above-mentioned form of the event name directly behind the object, jquery also provides the binding method for the event, which we can bind to the object: $ ("Input[type=button]"). Bind ("click", Function () {}); Of course, function () {} can be replaced with a defined global function name. $ ("Input[type=button]"). Bind ("click", functionname), and Bind is the Undo event (Unbind), as with bind, of course, Unbind do not necessarily have to fill in the functionname.  under the special point of the jquery event to do a simple description:bind/unbind  binding and undoing an event of an object delegate/undelegate   No object attaches one or more events, unlike bind, this object can not exist, as long as the object is added later, it will also automatically bind the event. live/die  attaching and undoing an event to an object, similar to delegate/undelegate   The following set of events is not the same as the event above: Load: Can be bound to a Window object or can be bound to a jquery pairThe unload can only be bound on the Window object and is not a revocation of the Load event, and the Unload event is emitted when the following occurs: 1. Click on a link to leave the page 2. In the Address bar, type a new URL3. Using the Forward or Back buttons 4. Close the browser 5. Reload page   When it comes to event binding, we often encounter the problem of having to pass parameters in the event of a binding event. So how do we do it in jquery? In general, there are two ways to solve my problem: 1.
$ ("Input[type=button]"). Bind ("click", {Name: "button", value= "Params"},function (event) {alert (event.data.name);   });
2. Use closures. The relevant contents of the closing package will be covered in the next chapter, which is not discussed in this chapter. 3. There is also a way to use the jquery's. Data () method to pass parameters, but this approach of adding custom attributes cannot be too large, and it is not good to pass too many parameters. Here's a look at this approach. If an object's event requires parameters, you can use the. Data () method to add a value to the object itself before binding the event to the object. such as code:
$ ("#id"). Data (name, "value"), $ (#id). Click (function () {alert (this). Data ("name");});

The third method feels similar to adding hidden on the page, with very little personal use. As we have said before, our customary usage is select.do (). Do (). So in jquery, we can also do this, for an object, we can continuously bind events, get properties, change the style ...., we call it the chain syntax. For example:
-$ ("#demo").  attr ("Class", "Test").  css ("style", "Display:block").  text ("Hello word").  Click ( function () {//you can do something})  . bind ("Select", Function () {//you can do something}) ...
Iv. other than selectors and events, jquery gives us a number of ways to manipulate DOM elements, such as getting the attributes of an element, text, manipulating the style, modifying attributes, manipulating nodes, and so on. Here are some common jquery methods:. addclass (),. Append (), AppendTo (),. After (),. attr (),. InsertAfter (),. InsertAfter (),. InsertBefore (),. css (),. html (),. Text (),. Val (),. ReplaceAll (),. ReplaceWith (),. Remove (),. prepend (),. Prependto () ..... When working with DOM elements, we often operate on a set element, and inevitably we go through it. The method that it provides is recommended in jquery. each () to operate. Each function in JQuery has two, Jquery.each () and. each (). The two functions are not the same. each () is designed to traverse a JQuery object. The $.each () function can be used to iterate over any collection, whether it is a "name/Value" object (JavaScript Object) or an array. Give two examples to illustrate.
$ ("input", form). each (function () {if (attr () = = ("type") = = "Text") {alert ("Some actions can be made for a text box.  "); }});
var data=[{name: "Sherry", Value: "},{name": "Alex", Value: "+"}];$.each (Data,function () {alert (this). name);});
Let's talk about another jquery function:. Extend (). Usually, we can see that many of the jquery plug-in calls are in the $ method. XXXX () This form, but the name XXXX is not defined in jquery. Why can I use jquery's $ to invoke it? Here, extend this method plays a very important role. Here's a look at the code:
$.extend ({min:function (A, b) {return a < b?a:b;}, Max:function (A, b) {return a > b?a:b;}});

In this code we have defined two functions: Min and Max, and then we can call this form directly using $.min (10,20) and $.max (10,20).

Jquery.extend () This function is described as: merging the contents of two or more objects together into the first object. Its constructor is:

Jquery.extend ([deep], Target, Object1, [objectn])

From here we can see that the function of extend is to say that multiple objects are merged, and if Target is omitted, it will be merged into the jquery namespace by default.

Some people will have doubts about this parameter. Let's look at the following code:

var object1 = {  apple:0,  Banana: {weight:52, price:100},  Cherry:97};var object2 = {  Banana: {price:20 0},  durian:100};$.extend (Object1, object2);//object1 = = = {apple:0, banana: {price:200}, cherry:97, durian:100}
var object1 = {  apple:0,  Banana: {weight:52, price:100},  Cherry:97};var object2 = {  Banana: {price:20  0},  lime:100};$.extend (True, Object1, object2);//object1 = = = {apple:0, banana: {weight:52, price:200}, cherry:97, LIME:100}

As can be seen from the above example, if the property of the first object itself is an object or an array, it will be completely rewritten with the same key as the second object, and if it is the true first function argument, the object will be recursively merged.

Of course,. Extend () is an object that can be returned. Look at the following code:

var empty = {}var defaults = {validate:false, limit:5, Name: "foo"};var options = {validate:true, name: "Bar"};var Settings = $.extend (empty, defaults, options)//settings = = {validate:true, limit:5, Name: "Bar"}//empty = = {Validate : True, Limit:5, Name: "Bar"}

Speaking of merging, by the way Jquery.merge () function, or see the code more specific:

var first = [0,1,2,3];var second = [1,2,3,4,5];$.merge (first, second);//first=[0,1,2,3,1,2,3,4,5];

Merge merges two arrays of contents into the first array. is completely merged and does not have a weight.

V. Data interaction Finally, let's talk about jquery's data interaction. jquery provides us with quite a few ways to interact with the server asynchronously, which is what we often call Ajax. -jquery.ajax (URL, [settings])

URL: A URL string to contain the sending request.

Settings: An AJAX request setting that consists of a "{key: Value}".

Let's take a look at the list of commonly used setting:

-async//Boolean, whether synchronized. Cross-domain requests and datatype: "JSONP" requests do not support synchronous operations. -complete (JQXHR, textstatus)//function is executed at completion, regardless of success or failure-data//object,string  {} Required Parameters-datatype//string ("xml", " HTML "," script "," JSON "," Jsonp "," text "), the return type has multiple when separated by a space-error (JQXHR, Textstatus, Errorthrown)//function occurs when the error is executed (NULL, "Timeout", "Error", "Abort" and "ParserError")-success (data, Textstatus, JQXHR)//function request succeeds after executing-type//string get/post, PUT and DELETE can also be used, but only some browsers support-url//string requests that require an address-timeout//number is set to the execution time of the timeout-statuscode//Map performs the action according to the status code returned by the function. The method is called: StatusCode: {404:function () {alert (' Page not Found ');} -jsonp//string overrides the name of the callback function in a JSONP request. This value is used instead of "callback=?" The "Callback" section in the URL parameter of this get or POST request-cache//whether the Boolean is enabled for browser caching-beforesend (JQXHR, settings)//function request before the Send call

The following two cases are written:

$.ajax ({url: ' ajax/test.html ', success:function (data) {$ ('. Result '). HTML (data);}     });
var jqxhr = $.ajax ({url: "ajax/test.html"})             . Success (function () {alert ("Success");})            . Error (function () {alert ("error");})             . Complete (function () {alert (' Complete ');}); Jqxhr.beforesend (function () {alert ("Beforesend");});

Both of these formulations are supported.

There are also two simplified versions of. Ajax ():

Jquery.get ()

Jquery.post ()

Equivalent to
$.ajax ({url:url,data:data,success:success,datatype:datatype});

Due to browser security restrictions, most requests cannot successfully retrieve data from different domains, subdomains, or protocols. But there are two forms of data (DataType) that are not subject to this limitation: script and Jsonp, and they have two shorthand quick call methods:

Jquery.getscript ()

Jquery.getjson ()

Both of these methods have stepped out of the browser's security restrictions, so be cautious. If the caller is not a Web site you trust, do not use this method because it may pose a considerable risk to your site, they will execute the requested content, and the specific content can be found in the garden other Daniel share.

Finally say a method:. Load ().

This is similar to Jquery.get (), unlike the. Load () is not a global function, and this method is not used to request data. The load () method sets the returned HTML content data to a matching node, so we often use it to load HTML fragments.

The thing about jquery is here, and here I'm just taking notes as a learning note, and a lot of the content is not being studied. I have been looking at other people's experiences before, and seldom write my own things. If there is falsehood, please correct me. Since I've been working on some of the front-end developments lately, there's been a lot of contact with JavaScript, so my next article is going to write something about JavaScript.

[Turn from setting] magical jquery

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.