JavaScript jQuery entry Review 2, javascriptjquery

Source: Internet
Author: User

JavaScript jQuery entry Review 2, javascriptjquery
JQuery slide

JQuery allows you to create sliding effects on elements.

  • SlideDown () slide down the element.
  • SlideUp () slides up the element.
  • SlideToggle () switches between the slideDown () and slideUp () methods.
  • $ (Selector). slide (speed, callback );
    {
    The optional speed parameter specifies the duration of the effect. It can take the following values: "slow", "fast", or millisecond.
    The optional callback parameter is the name of the function executed after sliding.
    }
JQuery Animation 

The jQuery animate () method is used to create custom animations.
Syntax:

$ (Selector). animate ({params}, speed, callback); // required params parameter definitions form the CSS attributes of the animation. // The optional speed parameter specifies the duration of the effect. It can take the following values: "slow", "fast", or millisecond. // The optional callback parameter is the name of the function executed after the animation is completed.

By default, all HTML elements are static and cannot be moved. To operate the position, first set the position attribute of the element CSS to relative, fixed, or absolute.
JQuery animate ()-Ability to operate on multiple attributes
To generate a Color animation, You need to download the Color animation plug-in from jQuery.com.
JQuery animate ()-Use Relative Value
You can also define a relative value (this value is relative to the current value of the element ). + = Or-= must be added before the value:

JQuery animate ()-Use predefined values
You can even set the animation value of an attribute to "show", "hide", or "toggle ":

$("button").click(function(){  $("div").animate({    height:'toggle'  });});

JQuery animate ()-Use the queue Function
By default, jQuery provides the queue function for animation.
This means that if multiple animate () calls are written after each other, jQuery will create an "internal" queue containing these method calls. Then run these animate calls one by one.

Ex1, ex2

JQuery stop ()

The jQuery stop () method is used to stop an animation or effect before they are completed.

The stop () method applies to all jQuery effect functions, including sliding, fade-in and fade-out, and custom animations.

$(selector).stop(stopAll, goToEnd);

The optional stopAll parameter specifies whether to clear the animation queue. The default value is false, that is, only the animation that stops the activity allows any animations that are placed in the queue to be executed backward.

The optional goToEnd parameter specifies whether the current animation is completed immediately. The default value 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 here ----});

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 processing function, and place all event processing functions in the document ready event processor.

Hide/show/toogle

$(selector).hide(speed, callback);$(selector).show(speed, callback);$(selector).toggle(speed, callback);

The optional speed parameter specifies the hidden/display speed. The value can be "slow", "fast", or millisecond.
The optional callback parameter is the name of the function executed after the function is hidden, displayed, or switched.

JQuery events
Event Function Bind a function
$ (Document). ready (function) Bind the function to the ready event of the document (when the document is loaded)
$ (Selector). click (function) Click events that trigger or bind a function to the selected Element
$ (Selector). dblclick (function) Double-click event that triggers or binds a function to the selected Element
$ (Selector). focus (function) Events that trigger or bind a function to the retrieved focus of the selected Element
$ (Selector). mouseover (function) A mouse hover event that triggers or binds a function to the selected element.
JQuery Fading

JQuery allows you to fade in and out elements.

JQuery has the following four fade methods:

  • FadeIn ()
  • FadeOut ()
  • FadeToggle ()
  • FadeTo ()

The jQuery fadeTo () method allows gradient to be a given opacity (value between 0 and 1 ).

$(selector).fadeTo(speed,opacity,callback);

RequiredThe speed parameter specifies the duration of the effect. It can take the following values: "slow", "fast", or millisecond.
RequiredThe opacity parameter sets the fade-in and fade-out effect to the specified opacity (value between 0 and 1 ).
OptionalThe callback parameter is the name of the function executed after the function is completed.

Because JavaScript statements (commands) are executed one by one, the animated statements may produce errors or page conflicts in order, because the animation is not completed yet.

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

Ajax

Get the Ajax-HttpRequest object:

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

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

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

$(selector).load(URL, data, callback);
  • Required URLThe parameter specifies the URL you want to load.
  • Optional DataThe set of query string key/value pairs that are required to be sent together with the request.
  • Optional CallbackThe parameter is the name of the function executed after the load () method is complete.

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

The following example loads the content of the id = "p1" element in the "demo_test.txt" file to 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 is complete. The callback function can set different parameters:

  • ResponseTxt-Contains the result when the call is successful.
  • StatusTXT-Including the call status
  • Xhr-Contains the XMLHttpRequest object.

The following example shows a prompt box after the load () method is complete. If the load () method is successful, "external content loaded successfully" is displayed !", 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 for request-response on the client and server are GET and POST.

  • GET-request data from the specified resource
  • POST-submit 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 obtain data from the server. However, the POST method does not cache data and is often used to send data together with requests.

Get ():

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

RequiredURLThe parameter specifies the URL you want to request.

OptionalCallbackThe parameter is the name of the function executed after the request is successful. The first callback parameter contains the content on the requested page, and the second callback parameter contains the Request status.

Post ():

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

RequiredURLThe parameter specifies the URL you want to request.

OptionalDataParameters are required together with the data sent by the request.

OptionalCallbackThe parameter is the name of the function executed after the request is successful. The first callback parameter contains the content of the requested page, while the second parameter contains the Request status.

Instance:

$("button").click(function(){  $.post("demo_test_post.asp",  {    name:"Donald Duck",    city:"Duckburg"  },  function(data,status){    alert("Data: " + data + "\nStatus: " + status);  });});

More

___________________________________________________________________________________

Operate CSS using jQuery
  • AddClass ()-add one or more classes to the selected Element
  • RemoveClass ()-delete one or more classes from the selected Element
  • ToggleClass ()-Adds or deletes the selected element to/from the switch operation.
  • Css ()-sets or returns one or more style attributes of the selected element.
JQuery css ()
Css ("propertyname"); // return the CSS attribute css ("propertyname", "value"); // set the CSS attribute css ({"propertyname": "value ", "propertyname": "value ",...}); // set multiple CSS attributes
JQuery width | height

JQuery provides an important way to process multiple dimensions:

  • Width () sets or returns the width of an element (excluding the padding, border, or margin ).
  • Height () sets or returns the height of an element (excluding the padding, border, or margin ).
  • InnerWidth () returns the width (including the padding) of the element ).
  • InnerHeight () returns the height of the element (including the padding ).
  • OuterWidth () returns the width of the element (including the padding, border, and margin ).
  • OuterHeight () returns the height of an element, including the padding, border, and margin ).

Set Value

$("#div1").width(500).height(500); 
$(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 requests to the server, use the open () and send () Methods of the XMLHttpRequest object:

Method Description
Open (Method,Url,Async)

Specifies the request type, URL, and whether to asynchronously process the request.

  • Method: Request type; GET or POST
  • Url: File location on the server
  • Async: True (asynchronous) or false (synchronous)
Send (String)

Send the request to the server.

  • String: Used 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();

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)

Add an HTTP header to the request.

  • Header: Name of the specified Header
  • Value: Specifies the header value.
GET or POST

Use POST requests in the following cases (the Post method does not produce cache ):

  • Unable to use cached files (updating files or databases on the server)
  • Send large amounts of data to the server (there is no limit on the size of POST data)
  • When sending user input containing unknown characters, POST is more stable and reliable than GET.
  • The Post method is used to transmit parameters, such as registration and submission;

If the XMLHttpRequest object is used for AJAX, The async parameter of its open () method must be set to true:
Through AJAX, JavaScript does not need to wait for the response from the server. Instead, it executes other scripts while waiting for the response from the server. When the response is ready, it processes the response.

Async = true/false

When async = true is used, specify the function to be executed when the response is in the ready state of 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 attribute of the XMLHttpRequest object.

Attribute Description
ResponseText Obtain response data in string format.
ResponseXML Obtain response data in XML format.

1. If the response from the server is not XML, use the responseText attribute.

The responseText property returns a string-type response, 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 attribute:

For example, request the 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 event

When a request is sent to the server, we need to execute some response-based tasks. When the readyState changes, the onreadystatechange event is triggered. The readyState attribute contains the status information of XMLHttpRequest.

The following are three important attributes of the XMLHttpRequest object:

Attribute Description
Onreadystatechange A storage function (or function name) that is called whenever the readyState attribute changes.
ReadyState

XMLHttpRequest status. Changes from 0 to 4.

  • 0: the request is not initialized.
  • 1: The server connection has been established.
  • 2: The request has been received
  • 3: The request is being processed
  • 4: The request is complete and the response is ready.
Status

200: "OK"

404: Page not found

In the onreadystatechange event, we specify the tasks executed when the server responds to the prepared tasks.

When readyState is 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 four times, corresponding to each change of readyState.

Use the Callback function

The callback function is a function that is passed to another function as a parameter.

If there are multiple AJAX tasks on the website, you should compile a standard function for creating the XMLHttpRequest object and call this function for each AJAX task.

This function call should contain URLs and tasks executed when the onreadystatechange event occurs (each call may be different ):

 

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.