JavaScript JQuery Primer Review 2

Source: Internet
Author: User
Tags html form

JQuery Swipe

With jquery, you can create a sliding effect on an element.

    • Slidedown () Slide the element down.
    • Slideup () Slide the element up.
    • Slidetoggle () Toggles between the Slidedown () and the Slideup () method.
    • $ (selector). Slide (Speed,callback);
      {
      The optional speed parameter specifies the length of the effect. It can take the following values: "Slow", "fast", or milliseconds.
      The optional callback parameter is the name of the function that is executed after the slide is completed.
      }
jQuery Animations

The JQuery animate () method is used to create custom animations.
Grammar:

$ (selector). Animate ({params}, speed, callback); // the required params parameter defines the CSS property that forms the animation.  //  The optional speed parameter specifies the length of the effect. It can take the following values: "Slow", "fast", or milliseconds. the //  Optional Callback parameter is the name of the function that is executed after the animation is completed. 

By default, the location of all HTML elements is static and cannot be moved. To manipulate the location, remember to first set the position property of the element's CSS to relative, fixed, or absolute.
JQuery animate ()- ability to manipulate multiple properties
If you need to generate color animations, you need to download the color animations plugin from jquery.com.
JQuery animate ()- using relative values
You can also define a relative value (this value relative to the current value of the element). You need to precede the value with + = or-=:

JQuery animate ()- use predefined values
You can even set the animation value of a property to "show", "Hide", or "toggle":

$ ("button"). Click (function() {$ ("div"). Animate ({height:' toggle ' }) ;

JQuery animate ()- Use the queue feature
By default, JQuery provides queue functionality for animations.
This means that if you write multiple animate () calls after each other, JQuery creates an "internal" queue that contains these method calls. These animate calls are then run individually.

Ex1,ex2

JQuery Stop ()

The JQuery Stop () method is used to stop animations or effects before they are finished.

The Stop () method applies to all JQuery effect functions, including sliding, fading, and custom animations.

$ (selector). Stop (StopAll, gotoend);

The optional StopAll parameter specifies whether the animation queue should be cleared. The default is false, which stops only active animations, allowing any queued animation to be executed backwards.

The optional gotoend parameter specifies whether to complete the current animation immediately. The default is False.

By default, stop () clears the current animation specified on the selected element.

Events and Methods

Document-Ready functions

$ (document). Ready (function() {---jQuery functions go----});

This is to prevent the document from running JQuery code before it is fully loaded (ready). If you run the function before the document is fully loaded, the operation may fail.

Place all JQuery code in the event handler and place all event handlers in the document-ready event handler

Hide/show/toogle

$ (selector). Hide (speed, callback); $ (selector). Show (speed, callback); $ (selector). Toggle (speed, callback);

The optional speed parameter specifies the rate of concealment/display, which can take the following values: "Slow", "fast", or milliseconds.
The optional callback parameter is the name of the function that is executed after the hide or display or switch is complete.

JQuery Events
Event function bind function to
$ (document). Ready (function) Bind a function to a document's Ready event (when the document finishes loading)
$ (selector). Click (function) A click event that triggers or binds a function to the selected element
$ (selector). DblClick (function) A double-click event that triggers or binds a function to the selected element
$ (selector). focus (function) Trigger or bind a function to the Focusable event of the selected element
$ (selector). MouseOver (function) Mouse hover event that triggers or binds a function to the selected element
JQuery Fading

With JQuery, you can implement the fade-out effect of elements.

JQuery has the following four methods of fade:

    • FadeIn ()
    • FadeOut ()
    • Fadetoggle ()
    • FadeTo ()

The JQuery FadeTo () method allows the gradient to be given opacity (values between 0 and 1).

$ (selector). FadeTo (Speed,opacity,callback);

Required for The speed parameter specifies the length of the effect. It can take the following values: "Slow", "fast", or milliseconds.
Required for The opacity parameter sets the fade effect to the given opacity (values between 0 and 1).
an optional The callback parameter is the name of the function that executes after the function completes.

Because JavaScript statements (directives) are executed one-at-a--in order, the statements after the animation can produce errors or page conflicts because the animation is not yet complete.

To avoid this situation, you can add the Callback function as a parameter. If you want to execute the statement after a function that involves animation, use the callback function.

Ajax

Get Ajax-httprequest object:

Htmlobj=$.ajax ({url: "/jquery/test1.txt", Async:false});
JQuery load ()

The JQuery load () method is a simple but powerful AJAX method.

The load () method loads the data from the server and puts the returned data into the selected element.

$ (selector). Load (URL, data, callback);
    • Required for The URL parameter specifies the URL that you want to load.
    • an optional The data parameter specifies the collection of query string key/value pairs that are sent with the request.
    • an optional The callback parameter is the name of the function that is executed after the load () method completes.

Note: You can also add the JQuery selector to the URL parameter.

The following example loads the contents of the id= "P1" element in the "Demo_test.txt" file into the specified <div> element:

$ ("#div1"). Load ("Demo_test.txt #p1");

The optional callback parameter specifies the callback function to be allowed after the load () method completes. The callback function can set different parameters:

    • responsetxt -Contains the contents of the result when the call succeeds
    • statustxt -Contains the state of the call
    • xhr -Contains XMLHttpRequest objects

The following example displays a prompt box after the load () method finishes. If the load () method is successful, the "External content loading succeeded!" is displayed. , and if it fails, an error message is displayed:

$ ("button"). Click (function () {$ ("#div1"). Load ("Demo_test.txt", Function (Responsetxt, statustxt, XHR) {
if (statustxt== "Success") alert ("External content loaded successfully!") ");
if (statustxt== "error") Alert ("Error:" +xhr.status+ ":" +xhr.statustext); });});
HTTP Request: GET vs POST

Two common methods of requesting-responding on the client and server side are GET and POST.

    • GET-Request data from the specified resource
    • POST-submits the data to be processed to the specified resource

Get is basically used to get (retrieve) data from the server. Note: The GET method may return cached data.

POST can also be used to fetch data from the server. However, the POST method does not cache data and is often used to send data together with the request.

Get ():

$.get (URL, callback:function(data, status));

The required URL parameter specifies the URL that you want to request.

The optional callback parameter is the name of the function that executes after the request succeeds. The first callback parameter contains the contents of the requested page, and the second callback parameter holds the requested State.

Post ():

$.post (URL, data, callback:function(data, status));

The required URL parameter specifies the URL that you want to request.

The optional data parameter specifies the information to be sent along with the request.

The optional callback parameter is the name of the function that executes after the request succeeds. The first callback parameter holds the contents of the requested page, while the second parameter holds the requested State.

Instance:

$ ("button"). Click (function() {  $.post ("demo_test_post.asp",  {    name:" Donald Duck ", City    :" Duckburg "  },  function(data,status) {    Alert ("data:" + Data + "\nstatus:" + status);  } );

More

___________________________________________________________________________________

JQuery Operation CSS
    • AddClass ()-adds one or more classes to the selected element
    • Removeclass ()-deletes one or more classes from the selected element
    • Toggleclass ()-switch operation to add/Remove classes for selected elements
    • CSS ()-Sets or returns one or more style attributes for the selected element.
JQuery css ()
// return to CSS properties // Set CSS Properties // set multiple CSS properties
JQuery Width|height

JQuery offers several important ways to handle dimensions:

    • Width () Sets or returns the width of the element (excluding padding, borders, or margins).
    • Height () Sets or returns the height of the element (excluding padding, borders, or margins).
    • Innerwidth () returns the width of the element, including the padding.
    • Innerheight () returns the height of the element, including the padding.
    • Outerwidth () returns the width of the element (including padding, borders, and margins).
    • Outerheight () returns the height of the element (including padding, borders, and margins).

Setting the value


$ (window/document). Width/height;  

XMLHttpRequest

var XMLHTTP; if (window. XMLHttpRequest) {//  code for ie7+, Firefox, Chrome, Opera, Safari    xmlhttp=new  XMLHttpRequest ();} Else {//  code for IE6, IE5    xmlhttp=new activexobject ("Microsoft.XMLHTTP ");}
Send a request to the server

To send the request to the server, we use the open () and send () methods of the XMLHttpRequest object:

Method Description
Open (method, url, async)

Specifies the type of request, the URL, and whether the request is processed asynchronously.

  • method: type of request; GET or POST
  • URL: The location of the file on the server
  • Async: True (asynchronous) or false (synchronous)
Send (string)

Sends the request to the server.

  • string: only for POST requests
GET request

If you want to send information through the GET method, add information to the URL:

Xmlhttp.open ("GET", "Demo_get2.asp?fname=bill&lname=gates",true); Xmlhttp.send ();
POST Request

A simple POST request:

Xmlhttp.open ("POST", "demo_post.asp",true); Xmlhttp.send ();

If you need to POST data like an HTML form, use setRequestHeader () to add an HTTP header. Then specify the data you want to send in the Send () method:

Xmlhttp.open ("POST", "ajax_test.asp",true); Xmlhttp.setrequestheader ("Content-type", " Application/x-www-form-urlencoded "); Xmlhttp.send (" fname=bill&lname=gates ");
Method Description
setRequestHeader (header, value)

Adds an HTTP header to the request.

  • header: Name of the specified header
  • Value: The values of the specified header
GET or POST

Use the POST request (the Post does not produce a cache) in the following cases:

    • Unable to use cache file (update file or database on server)
    • Send a large amount of data to the server (POST has no data volume limit)
    • Post is more stable and more reliable than GET when sending user input with unknown characters
    • Need to transfer parameters when using post, such as registration, submission;

The async parameter of the open () method must be set to True if the XMLHttpRequest object is to be used with AJAX:
Instead of waiting for a response from the server, the Ajax,javascript executes additional scripts while waiting for the server to respond, processing the response when it is ready.

Async = True/false

When using Async=true, specify the function to be executed when responding to the ready state in the onReadyStateChange event:
Note: When using Async=false, do not write the onreadystatechange function-put the code behind the Send () statement:

xmlhttp.onreadystatechange=function() {if (xmlhttp.readystate==4 && xmlhttp.status==200) {document.getElementById ("mydiv"). innerhtml=Xmlhttp.responsetext;}} Xmlhttp.open ("GET", "Test1.txt",true); Xmlhttp.send ();

Server response

To obtain a response from the server, use the ResponseText or Responsexml property of the XMLHttpRequest object.

Properties Description
ResponseText Gets the response data in the form of a string.
Responsexml Get the response data in XML form.

1. If the response from the server is not XML, use the ResponseText property.

The ResponseText property returns a response in the form of a string, so you can use:

document.getElementById ("Mydiv"). Innerhtml=xmlhttp.responsetext;

2. If the response from the server is XML and needs to be parsed as an XML object, use the Responsexml property:

such as: request Books.xml file, and parse the response

xmldoc=xmlhttp.responsexml;txt= ""; x=xmldoc.getelementsbytagname ("ARTIST");  for (i=0;i<x.length;i++)  {  txt=txt + x[i].childnodes[0].nodevalue + "<br/>";  } document.getElementById ("mydiv"). Innerhtml=txt;  
onReadyStateChange Events

When a request is sent to the server, we need to perform some response-based tasks. The onreadystatechange event is triggered whenever the readyState changes. The ReadyState attribute holds state information for XMLHttpRequest.

The following are three important properties of the XMLHttpRequest object:

Properties Description
onReadyStateChange The function (or function name) is called whenever the ReadyState property is changed.
ReadyState

The state of being xmlhttprequest. Vary from 0 to 4.

  • 0: Request not initialized
  • 1: Server Connection established
  • 2: Request received
  • 3: In Request processing
  • 4: The request is complete and the response is ready
Status

$: "OK"

404: Page Not Found

In the onReadyStateChange event, we specify the tasks that are performed when the server responds to readiness to be processed.

When ReadyState equals 4 and the status is 200, the response is ready:

xmlhttp.onreadystatechange=function()  {  if (xmlhttp.readystate==4 && xmlhttp.status==200)    {    document.getElementById ("mydiv"). innerhtml=xmlhttp.responsetext;    }  } 

Note: The onReadyStateChange event is triggered 4 times, corresponding to each change of the readyState.

Using the Callback function

The callback function is a function that is passed as an argument to another function.

If there are multiple AJAX tasks on the site, you should write a standard function for creating the XMLHttpRequest object and call it for each AJAX task.

The function call should contain the URL and the task that is performed when the onReadyStateChange event occurs (each call may be different):

JavaScript JQuery Primer Review 2

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.