javascript--Learning Notes (ii) __java

Source: Internet
Author: User
Tags assert event listener send cookies
JavaScript Console ObjectConsole.log
This method is used to output information in the console window, which can receive multiple parameters and link their results to output
This method automatically adds line breaks at the end of the output
This method supports the format placeholder and replaces the format placeholder and output with the following arguments
Console.log supports the following placeholders:
%s string
%d integer If the given value is a floating-point number, rounding down
%i Integer If the given value is a floating-point number, rounding down
%f floating-point numbers
%o object to display the value of the object
%c CSS format string For example: ' color:red; Background:yellow; font-size:24px; ' Used to render the content of the output
Console.info and Console.debug
Console.info and Console.debug are all console.log aliases, and use exactly the same. Info output is preceded by a blue icon.
Console.warn and Console.error
Warn method output information, add a yellow triangle at the front, indicating warning
Error method output information, preceded by a red fork, indicating an error, and will show the stack of errors occurred
Console.table
For some composite data, it can be transformed into a table display
var languages = [
{Name: "JavaScript", FileExtension: ". js"},
{name: ' typescript ', fileextension: '. ts '},
{Name: "Coffeescript", FileExtension: ". Coffee"}
];
Console.table (languages);
The condition that the composite data is converted to a table is that it must have a primary key. For an array, the primary key is the number key, and for the object, the primary key is his outermost key.
Console.count ()
Used for counting, the number of times the output was invoked
Can accept the parameters of a string, as a label, to classify the number of executions
Console.dir and Console.dirxml
Used to output DOM elements
Console.assert (exp,string)
The Assert method receives two arguments, the first argument is an expression, the second argument is a string, and the second argument is output only if the first argument is false, otherwise there will be no result.
Console.time () Console.timeend ()
These two methods are used for timing and can calculate the exact time that an operation takes.
Receives a string parameter to define the name of the timer
Console.group Console.groupend console.groupcollapsed
Used to group displayed information in a group of information that can be folded and expanded with the mouse
Console.trace Console.clear
The trace method shows the calling path of the currently executing code in the stack
The clear method clears all output from the current console
JavaScript Object-orientedJavaScript uses constructors as templates for objects
var Vehicle = function () {
This.price = 1000;
};
Features of constructors:
The inside function body uses the This keyword to represent the object instance to be generated
When you build an object, you must invoke the vehicle function with the new command
To differentiate from ordinary functions, the first letter of the constructor name is usually capitalized.
this keyword
If a function is running in the global environment (not using new), this refers to the top-level object (the Window object in the browser)
You can approximate that this is a hidden parameter when all functions run, pointing to the runtime environment of the function
This in the constructor, refers to the instance object
Method of Binding this
JavaScript provides call, apply, bind three methods to toggle/fix the point of this.
Function.prototype.call
The call method for an instance of a function that specifies the point to which this is within the function (that is, the scope in which the function executes), and then calls the function in the specified scope.
The parameter of the call method should be an object. If the parameter is NULL, NULL, and undefined, the global object is passed in by default.
Call can accept more than one argument, and the first argument is the object to which this is directed. The arguments that follow are the parameters that are required when the function is called.
Function.prototype.apply
The Apply method behaves like the call method, and it is also the point that changes this, and then calls the function,
The difference is that it takes an array as an argument when the function executes.
JavaScript prototype ObjectsConstructors
JavaScript generates new objects through constructors. The properties and methods of the instance, which can be defined within the constructor.
Each object of JavaScript inherits another object. In addition to NULL, it has no prototype object of its own, and the prototype object is null
All properties and methods on the prototype object. Can be shared by derived objects
The purpose of a prototype object is to define the properties and methods shared by all instance objects
Prototype chain
function, read an object's properties, the JavaScript engine is looking for the object itself properties, can not find the prototype to find, and can not find, to prototype prototype to find, until the top of the object.prototype still can not find, return undefined
Constructor property
The prototype object has a constructor property, and the default point is to the constructor of the prototype object
instanceof operator
That indicates whether the specified object is an instance of a constructor, and returns a Boolean value
Because instanceof is valid for objects on the entire prototype chain, the same instance object may be an instance of multiple constructors
The instanceof operator can only be used with objects, not values of the original type (for example, string and number)
Object.getprototypeof ()
This method returns the prototype of an object
Object.setprototypeof ()
This method can set the prototype for an existing object and return a new object. Receives two parameters, one is an existing object, the other is a prototype object
Object.create ()
Used to generate a new object from a prototype object, which can be substituted for the command
He takes an object as a parameter and returns a new object that completely inherits the properties of the new person
isPrototypeOf ()
A prototype used to determine whether an object is another object
JavaScript Event ModelAddEventListener () The listener function of the binding event
The method receives three parameters:
Type: The name of the event
Listener: Listener function. When an event occurs, the listener function is called
Usecapture: Indicates whether the listener function is triggered during the capture phase
Instance:
function Hello () {
Console.log ("Hello");
}
var Button=document.getelementbyid (' btn ');
Button.addeventlistener (' click ', Hello,false)
Above is the button element, the listener function that binds the click event Hello
You can add multiple listener functions to the same event for the current object, and the functions are triggered in the order they were added
RemoveEventListener ()
Removes the listener function for the added event. parameter is consistent with AddEventListener
Dispatchevent ()
Triggers the specified event on the current node, triggering the execution of the listener function
The parameter of the method is an instance of an event object
var event=new event (' click ');
Button.dispatchevent (event);
Listener function
The listener function is the function that the program executes when the event occurs.
Three ways to bind an event to a listener function:
1 on-Properties of HTML tags
Allows you to define the listener code for an event directly in the attribute of the element label
2 event properties for ELEMENT nodes
The element node object has event properties and can also specify the listener function
3 Using the AddEventListener method
This method of the element node, document node, and window object to define the listener function for the event
The spread of events is divided into three stages
Capture phase: Conduction from Window object to target node
Target phase; Triggers on the target node
Bubbling phase: Transmitting the Window object back from the target node
Stoppropagation prevents the listener from propagating up (to the parent node), but appears in the function event.stoppropagation, blocking only the current listener function
Cannot block the triggering of other bound listener functions. At this point, you can use the Stopimmediatepropagation method to block all of the listener functions that are bound to this event on the node.
Event Object
When an event occurs, an event object is generated and passed as a parameter to the listener function
The event object itself is a constructor that can be used to generate a new instance.
The event constructor receives two parameters: The first argument is a string that represents the name of the event, and the second parameter is an object that represents the object configuration of the event
The second parameter contains two properties: Bubbles: A Boolean value that indicates whether the event object is bubbling; Cancleable: A Boolean value that indicates whether the event can be canceled
Event.eventphase
This property returns an integer value that represents the node where the event is currently.
0: The event does not occur at this time
1: is currently in the capture phase
2: The event arrives at the target node
3: Event is in a bubbling node
Event.preventdefault
The Preventdefault method cancels the browser's default behavior for the current event, and the method takes effect if the Cancelable property is True
Using the Preventdefault method, the default behavior of the event is not performed.
Event.currenttarget
Returns the node where the event is currently located, that is, the node to which the listener function currently executing is being bound
Event.target
Returns the node that triggered the event
types of JavaScript eventsMouse events
Mouse click Definition: The user completes a MouseDown action and MouseUp action in the same position, their triggering order is: MouseDown, MouseUp, MouseClick
MouseUp: Event triggers when a pressed mouse button is released
MouseDown: Event triggered when the mouse button is pressed
MouseMove: Event triggers when the mouse moves inside a node
MouseOver and MouseEnter events are triggered when the mouse enters a node. Difference, the MouseEnter event triggers only once
Mouseout and MouseLeave events, are triggered when the mouse leaves a node, the difference, the Mouseout event bubbles, the child node Mouseout event bubbles to the parent node, which triggers the parent node's Mouseout event.
ContextMenu event triggers when the right mouse button is clicked on a node
The wheel event is the event associated with the mouse wheel, which is triggered by the scrolling wheel of the user's mouse. This event inherits the properties of MouseEvent, Uievent, event
There are several attributes of your own:
DeltaX: Returns a numeric value indicating the horizontal scrolling volume of the scroll
DeltaY: Returns a numeric value that represents the amount of scrolling vertical scrolling
Deltaz: Returns a numeric value indicating the amount of scroll z-axis scrolling
Deltamode: Returns a number that represents the unit of the scroll. 0 for pixels, 1 for rows, 2 for pages
Keyboard events
There are three main events: KeyDown keypress KeyUp
KeyDown: Events triggered when the keyboard is pressed
KeyPress: Just press the key not CTRL, ALT, SHIFT, and meta (Windows key), then trigger the KeyPress event
KeyUp: Events triggered when the keyboard is released
Keyboard events are represented using the KeyboardEvent object, which inherits Uievent, MouseEvent objects
The event contains two properties:
The key property returns a string representing the pressed key name;
The CharCode property returns a value that represents the Unicode value of the KeyPress event key
Progress events
A progress event is used to describe the process of an event's progress. Progressevent constructor, used to generate an instance of a progress event
Drag events
means that the user presses the mouse button on an object, drags it to another location, then releases the mouse and places the object there
In HTML pages, other than the element node is not dragged by default, others (Pictures, links, selected text) can be dragged directly.
To allow element elements to be dragged, you can set the Draggable property of the node to true.
JavaScript CSS ActionsCSS is responsible for the visual effects of the page
JavaScript is responsible for interacting with the user's behavior
The style object of the element node object, with a Csstext property that can read and write and delete the entire style
var divstyle=document.queryselector (' div '). style;
divstyle.csstext= "Background-color:yellow;" + ' border:1px solid black '
Style object has three methods to read and write inline CSS rules
SetProperty (Propertyname,value): Set a CSS Property
GetProperty (PropertyName) Gets a CSS property
Removeproperty (PropertyName) Deletes a CSS property
To modify the style of a node:
var divstyle = document.queryselector (' div '). style; Get a Style object for a node element
Divstyle.setproperty ("Background-color", "Red")
Divstyle.backgroundcolor= "Red"
divstyle.csstext= "background-color:red;"
window.getComputedStyle ()
Inline styles have the highest precedence and change inline styles, which are usually reflected immediately. But the final style of the page elements is calculated by combining various rules.
The window.getComputedStyle method, which is used to return this rule, receives a DOM node object as a parameter and returns an object that contains the final style information for that node
For example: window.getComputedStyle (document.queryselector (' div ')). BackgroundColor
or window.getComputedStyle (document.queryselector (' div ')). GetPropertyValue ("Background-color")
JavaScript AJAXAjax sends an HTTP request through the native XMLHttpRequest object, and then processes the data returned by the server.
Ajax can be either a synchronous request or an asynchronous request. In most cases, asynchronous requests, because synchronous AJAX requests have a "blocking effect" on the browser
The XMLHttpRequest object is used to pass data between the browser and the server
Once you get the data returned by the server, Ajax does not refresh the entire page, just update the relevant parts
Note: Ajax can only send HTTP requests to the same source URL (protocol, domain name, port), and if a cross feed request is issued, an error is made
XMLHttpRequest can submit various data, including strings and binaries, and support both the HTTP protocol and the file and FTP protocols
Open
The XMLHttpRequest Open method specifies the HTTP verb, the URL of the request, and whether it is synchronized
Five parameters accepted altogether
void Open (
String method,
String URL,
Optional Boolean async,
Optional String user,
Optional String password
);
Method: denotes an HTTP verb, such as get post put delete head
URL: Indicates the URL that the request sends
Async: Indicates whether the request is asynchronous and the default is True
User: Indicates the username used for authentication
Password: Represents a password for authentication
The open method makes a request to the specified URL, and the Send method sends the actual data
Send
For sending an HTTP request, the parameter of the method is the data sent
Sending an instance with parameters
Ajax.open (' Get '
, ' http://www.example.com/somepage.php?id= ' + encodeuricomponent (ID)
, True
);
Equal to
var data = ' id= ' + encodeuricomponent (ID));
Ajax.open (' Get ', ' http://www.example.com/somepage.php ', true);
Ajax.send (data);
It is to be noted that. : All XMLHttpRequest listener events must be set before the Send () method call
Send can also accept Formdata type
Formdata types can be used to construct form data
var formData =new FormData ();
Formdata.append (' username ', ' John ')
var xhr=new xmlhttprequest ();
Xhr.open ("Post", "/register");
Xhr.send (FormData)

Formdata can also generate existing form constructs
<form id= ' registration ' name= ' registration ' action= '/register ' >
<input type= ' text ' name= ' username ' value= ' john ' >
<input type= ' email ' name= ' email ' value= ' zhangsan@example.com ' >
<input type= ' number ' name= ' Birthdate ' value= ' 1940 ' >
<input type= ' Submit ' onclick= ' return Sendform (this.form); ' >
</form>
function Sendform (form) {
var formdata=new formData (form);
var xhr=new xmlhttprequest ();
Xhr.open ("Post", "/register");
Xhr.send (FormData)
}
XMLHttpRequest Instance Properties
ReadyState
Use an integer and a constant to indicate the current state of the XMLHttpRequest request
0, corresponding to unsent, indicates that the XMLHttpRequest instance has been generated, but the open () method has not yet called
1, corresponding to opened, indicates that the Send () method has not been called
2, corresponding to the headers-received, indicates that the Send () method has been executed, and that the header information and status codes have been received.
3, corresponding to the loading, indicating that the data is receiving the body part from the server side
4, corresponding to the done, indicating that the server data has been fully accepted, or this acceptance has failed
onReadyStateChange
This attribute points to a callback function that is invoked when the ReadyStateChange event occurs, and XMLHttpRequest
The ReadyState property of the instance will also change
Response
property is read-only, returns the received data body, the type is determined by the value of the Responsetype property
If the request is not successful or the data is incomplete, the property equals null
Responsetype
Specify the type of server return data
"", String
"Arraybuffer": Arraybuffer Object
"Blob": BLOB objects are suitable for reading binary data, such as picture files
"Document": Document object, suitable for returning an XML document
"JSON" JSON object
"Text" string, suitable for most cases, direct processing of text is easier
ResponseText
Returns the string received from the server
If the returned data format is JSON, you can use the ResponseText property
var Data=ajax.responsetext;
Data=json.parse (data);
Responsexml
Returns the Document object received by the server, and the returned data is parsed directly into a DOM object
var data=ajax.responsexml;
var chapters=data.getelementsbytagname ("chapter");
Status
property is read-only, representing the HTTP status code obtained for this request, an integer that successfully returns 200
OK, access is normal.
Permanently, moved, permanently moved
302, move temporarily, temporarily moved
304, not Modified, unmodified
307, temporary Redirect, temporarily redirected
401, Unauthorized, unauthorized
403, Forbidden, no access
404, not Found, no specified URL found
Internal Server error.
StatusText
property is read-only, returning a string that represents the prompt for the server to send status, containing the entire state information. For example, "OK"
Timeout
Property equals an integer, representing how many milliseconds, and then automatically terminates if the result is still not obtained. If the property equals 0, there is no time limit.
Event Listener Interface
You can specify a listener interface for the following events
Onloadstart Request issued
OnProgress is sending and loading data
The onabort request was aborted, such as when the user invoked the Abort () method
OnError request failed
OnLoad request completed successfully
OnTimeOut user-specified time limit expires, request not completed
Onloadend request complete, regardless of outcome or failure
Withcredentials
This property is a bool value that indicates whether the user information is included in the request when the Cross-domain request is requested. If you need to send cookies across domain Ajax, you need to open the Withcredentials=true
In order for this attribute to take effect, the server needs to display the return access-control-allow-credential this information
Access-control-allow-credential:true
getAllResponseHeaders ()
Returns all HTTP header information from the server, formatted as a string
Getresposneheader ("FIELDNAME")
Returns the value of the field specified by the HTTP header information
JavaScript Document NodeThe document node is the root node of the documents, each of which has its own document node
Internal Node Properties:
Document.doctype is an object that contains the current document type
Document.firstchild returns the first node of the document, usually the declaration of the document type
Document.documentelement returns the root node of the current document, usually the Document.defaultview returns the Window object that contains the Document object
Document.head returns the head node of the current document
Document.body returns the body node of the current document
Document.activeelement returns the element that receives focus in the current document
Node Collection Properties
Document.links sets the set of a and area elements for href
Document.forms Form Elements Collection
Document.images Elements Collection
Document.embeds embedded object collection that embed tag
The above four properties return all the Htmlcollection objects
If the above four elements have IDs or name attributes, you can refer to the four properties above
<form name= "MyForm" >//HTML code
Document.myform===document.forms.myform
Document.scripts returns all scripts for the current document
The Document.stylesheets property returns an array-like object that represents all the style sheets for the current page
Document. URL returns a string representing the URL of the current document
Document.domain returns the domain name of the current document
Document.lastmodified returns the timestamp of the last modification of the current document, formatted as a string
If you want to compare, convert it to date format date.parse (document.lastmodify)
Document.location returns the Location object that provides URL information for the current document
Document.title the title of the current document can be modified
The Document.characterset property returns the character set that renders the current document, such as UTF-8
Document.readystate returns the status of the current document (loading, interactive, complete)
The Document.compatmode property returns the mode in which the browser processes the document (Backcompat backward compatibility mode Css1compat strict mode)
The Document.cookie property is used to manipulate the cookie of the browser
Read and write related methods
Document.open () is used to create a new document, provide write method writes, equal to clear the current document, and write back the content
Document.close () to close the Open method new document
Document.Write is used to write content to the current document, and as long as there is no close, the content it writes is appended to the existing content
Ways to find nodes
Document.queryselector () returns only the first matching
Document.queryselectorall () returns all matching
The method receives the CSS selector as a parameter and returns the element node that matches the selector.
document.getElementsByTagName ()
This method returns an element of all the specified HTML tags, returning a Htmlcollection object
Document.getelementsbyclassname ()
Returns the elements that all class names meet the specified criteria
Document.getelementsbyname ()
Select the HTML element that owns the Name property and return an object that resembles an array
document.getElementById ()
Returns the element node that matches the specified ID attribute
Document.elementfrompoint ()
Returns the element child node at the top of the page's specified position
Methods of generating nodes
Document.createelement ()
This method is used to generate page element nodes
var newdiv=document.createelement (' div ');
document.createTextNode ()
This method is used to generate text nodes
var newcontent=document.createtextnode ("Hello")
Newdiv.appendchild (newcontent)
Document.createattribute ()
This method generates a new Property object node and returns
var a=document.createattribute ("My_attr")
A.value= "NewVal"
var Node=document.getelementbyid ("div")
Node.setattributenode (a)


Reference: http://javascript.ruanyifeng.com/bom/engine.html
Related Article

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.