JavaScript Learning Notes (iii) BOM and Dom detailed knowledge _ Basics

Source: Internet
Author: User
Tags event listener object model tag name time interval browser cache

JS composition

As we all know, javascript there are three components ECMAScript , DOM and, BOM depending on the host (browser), the specific manifestations are not the same, IE and other browser styles are different.

1. DOM is the standard of the web; [Standard for all browsers to comply]
2. BOM is the various browser vendors according to DOM
Implementation on the respective browsers; [behaves differently for different browser definitions, different implementations]
3. Window is a BOM object, not a JS object;

DOM(Document Object model) is HTML XML the and Application Interface ( API ).

BOMPrimarily handles browser windows and frames, but typically browser-specific JavaScript extensions are considered part of the BOM. These extensions include:

 pop-up browser window to move, close browser window, and resize window to provide Web browser details the screen object that provides the user's screen resolution details the support IE extends to the cookie BOM, add the ActiveXObject class, you can instantiate ActiveX objects 
through JavaScript

javacsriptis BOM to access, control, and modify the client (browser) by accessing (Browser object Model) objects, because BOM the window document properties and methods of the Window object are directly available and perceived, so they can be directly used windowobject document , which document enables you to access, retrieve, and modify the content and structure of the XHTML document through attributes. Because document the object is also the root node of the DOM (Document Object model) model. It can be said that the BOM contains DOM (objects), the browser provided to give access to the BOM object, from the BOM object to access the DOM object, so that JS can operate the browser and browser read the document. which
The DOM contains:window

Window object contains properties: Document, location, navigator, screen, history, frames the

document root node contains child nodes: forms, location, anchors, Images, Links

As window.document you can already see, the most fundamental object of the DOM is the child object of the BOM's Window object.

Difference: Dom describes the methods and interfaces for handling Web content, and the BOM describes the methods and interfaces that interact with the browser.

Understanding DOM

Let's take a look at the following code:

  <! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en"
 "http://www.w3.org/TR/xhtml1/DTD/ Xhtml1-transitional.dtd ">
   
 

To decompose HTML code into a DOM node hierarchy diagram:

 **html documents can be said to consist of a set of nodes, DOM nodes are: * *
1. Element node: Above,  
 

Node property Node Property nodename Returns a string whose contents are the names of the nodes NodeType returns an integer that represents the type of the given node NodeValue returns the current value of the given node

Traversal node tree traversal node tree childnodes returns an array, This array is composed of the child nodes of the given element FirstChild returns the first child node LastChild returns the last child node ParentNode returns the parent node of a given node nextsibling returns the next child node of a given node previoussibling returns the last of the given node Child nodes

DOM Operations DOM Operations createlement (Element) creates a new element node Creattextnode () creates a new text node containing the given text appendchild () Adds a new child section after the last node list of the specified node InsertBefore () inserts a given node in front of a given child node of a given element node removechild () deletes a child node from a given element replacechild () Replaces a child node in a given parent element with another node

Dom creates a tree to represent the document, describes methods and interfaces for handling Web content, gives developers unprecedented control over the content and structure of the document, and can easily delete, add, and replace nodes with the DOM API.

1. Access nodes

' var ohtml = Document.documentelement '/returns the document root node in XML and HTML document, Ohtml contains a/> object representing  
 

2. Characteristics and methods of node nodes

FirstChild//node, pointing to the first node in the ChildNodes list 
LastChild//node, pointing to the last node in the ChildNodes list parentnode 
//node, pointing to the parent section
ownerdocument//document, pointing to the document FirstChild//node that this node belongs 
to, points to the first node in the ChildNodes list LastChild  
//node, Point to the last node in the ChildNodes list  
parentnode//node, point to the parent node  
childnodes//nodelist, and the list of all child nodes 
Previoussibling/node, /point to the previous sibling node: If this node is the first node, then the value is null 
' nextSibling '//node, pointing to the latter sibling node: if this node is the last node, then the value is null 
' HasChildNodes () '//boolean, when childnodes contains one or more nodes, returns the truth value 

3.DOM Event

  Dom simultaneously two event models: bubbling events and Catch-type event 
  bubbling events: Events trigger 
  <body onclick= "Handleclick ()" In order from the most specific event target to the least specific event target > 
    The order of <div onclick= "Handleclick ()" >click me</div> 
  </body> 
  triggers is: div, body, HTML (IE 6.0 and Mozilla 1.0, Document, window (Mozilla 1.0) 

  capture event: The reverse process of the bubbling event, which triggers the event from the most imprecise object and then to the most accurate 
  The above example triggers the order that the document, the Div 
  DOM event model, the most unique nature is that the text node also triggers events (not in IE). 

4. event handler function/Listener function

 * * Event handler/listener function * * 
in javascript: 
var odiv = document.getElementById ("Div1"); 
Odiv.onclick = function () {//onclick only lowercase, default to bubbling event 
  alert ("clicked!"); 
} 

In HTML: 
<div onclick= "Javascript:alert (" clicked! ")" ></div>//onclick Case arbitrary 

IE event handlers attachevent () and DetachEvent ()

In IE, each element and window object has two methods: the attachEvent()和detachEvent() two methods accept two identical parameters, the event handler name and the event handler function, such as:

[Object].attachevent ("Name_of_event_handler", "Function_to_attach") 
[Object].detachevent ("Name_of_event_ Handler "," Function_to_remove ") 
var fnclick = function () { 
  alert (" clicked! "); 
} 
Odiv.attachevent ("onclick", Fnclick); Add event handler function 
odiv.attachevent ("onclick", fnclickanother);//You can add multiple event handler functions 
odiv.detachevent ("onclick", Fnclick); Removing an event handler function 

In the attachEvent() case of using a method, the event handler runs in the global scope, so this is equal to window.

Cross-browser event handlers

addHandler()和removeHandler()

addHandler()The method belongs to an object called Eventuntil () that accepts three identical parameters, the element to be manipulated, the event name, and the event handler function.

Event Type

* * Event Type * * 
 mouse events: Click, Dbclick, MouseDown, MouseUp, MouseOver, mouseout, MouseMove 
 keyboard events: KeyDown, KeyPress, KeyUp 
 HTML events: Load, unload, Abort, error, select, change, submit, Reset,
resize, scroll, focus, Blur

Event handlers

Programs that execute JavaScript code respond to events when they occur. In response to a specific event
The code being executed is called the event handler.

The syntax for using event handlers in HTML tags is:

Event handlers

An event is an action performed by a user or browser itself. such as click,mouseup,keydown,mouseover all the names of events. The function that responds to an event is called an event handler (event listener), and the event handler starts with the event handler that on click isonclick

DOM Level 0 Event handler

DOM Level 0 Event handler: The handler attribute that assigns a function to an event

<input type= "button" value= "Buttons 2" id= "Ben2"/>
     var btn2=document.getelementbyid (' btn2 '); Get Btn2 button Object
     Btn2.onclick      //Add the onclick attribute to btn2, and the property triggers an event handler

Btn2.onclick=function () {
}                    //Add anonymous function

Btn2.onclick=null      //delete onclick attribute

How do I stop bubbles?

Blocking bubbles has the following methods:

e.cancelBubble=true;
e.stopPropagation();
return false;

InnerText, InnerHTML, outerHTML, outertext

  InnerText, InnerHTML, outerhtml, outertext
  innertext: Text InnerHTML between start and end tags 
  : HTML code 
  that represents all elements and text of an element Like:<div><b>hello</b> World</div> 's innertext for Hello world,innerhtml for Hello World 
  outerText : The difference with the former is that the entire target node is replaced, and the problem returns the same content as InnerText 
  outerhtml: The difference with the former is that the entire target node is replaced, and the complete HTML code of the element is returned, including the element itself 

DOM Level 2 event handler

The DOM Level 2 event defines two methods for specifying and deleting the actions of an event handler. addEventListener()andremoveEventListener()

AddEventListener () and RemoveEventListener ()

In the DOM, AddEventListener () and RemoveEventListener () are used to allocate and remove event-handling functions, which, unlike IE, require three parameters: the event name, the function to be allocated, and the processing function to be used for the bubbling phase (false) or capture phase (true), the default is bubbling phase false 

[Object].addeventlistener ("Name_of_event", Fnhander,bcapture) 

[Object]. RemoveEventListener ("Name_of_event", fnhander,bcapture) 

var fnclick = function () { 
  alert ("clicked!"); 
} 
Odiv.addeventlistener ("onclick", Fnclick, false); Add event handler function 

Odiv.addeventlistener ("onclick", Fnclickanother, false);///As with IE, you can add more than one event handler function 

Odiv.removeeventlistener ("onclick", Fnclick, false); Remove event handler 

if you use AddEventListener () to add an event handler to the capture phase, you must indicate in RemoveEventListener () that it is the capture phase in order to properly remove 

the event handler function Odiv.onclick = Fnclick; 

Odiv.onclick = Fnclickanother; Using direct assignment, subsequent event handlers overwrite the preceding handler function 

Odiv.onclick = Fnclick; 

Odiv.addeventlistener ("onclick", Fnclickanother, false); are called sequentially and do not overwrite 

A picture of outhtml and innertext, InnerHTML:

DOM Basic Operational Thinking map

For more detailed XML Dom-element object properties and methods, visit the W3cshool

BOM section

BOMThe core is window , and the window object has a dual role, it is both through JS access to the browser window of an interface, but also a Global (global) object. This means that any objects, variables, and functions defined in the Web page are objects of window global .

Window.close (); Closes the window 

window.alert ("message");///pops up a system messages box with the OK button to display the specified text 

window.confirm ("Are you sure?"); A query dialog box with the OK and Cancel buttons pops up, returning a Boolean value of 

window.prompt ("What ' Your name?", "Default");//Prompt the user to enter information, accept two parameters, That is, the default value in text and text boxes that you want to display to the user, return the value in the text box as a function value 

window.status//You can make the text of the status bar temporarily change the 

window.defaultstatus//default status bar information. You can change the text 

window.settimeout ("alert (' xxx ')", 1000) before the user leaves the current page;//set to execute the specified code after the specified number of milliseconds, accept 2 parameters, code to execute, and the number 

of milliseconds to wait Window.cleartimeout ("ID"); Cancels a paused that has not yet been performed, passing the pause ID to it 

window.setinterval (function, 1000);////////////////////////////////////// 

Window.clearinterval ("ID"); Cancels a time interval, passing the interval ID to it 

window.history.go (-1);//access the history of the browser window, negative numbers are backwards, positive numbers are forward 

window.history.back ();/Ibid. 

Window.history.forward (); Ditto 

window.history.length//Can view the number of pages in history  

Document Object

Document object: is actually the property of the Window object, document = = Window.document is true and is the only object that belongs to both the BOM and the DOM 

document.lastmodified// Gets a string representing the date of the last modification of the page 

Document.referrer///is used to track the user from where the link 

document.title//Get the title of the current page, read and write 

document. URL//Get URL of current page, read/write 

document.anchors[0] or document.anchors["anchname"//Access all anchor in page 

Document.forms[0] or document.forms["formName"]//access all forms in the page 

document.images[0] or document.images["imgname"]//access all images 

on the page document.links [0] or document.links["linkname"]//access to all links in the page 

document.applets [0] or document.applets["Appletname" ]//Access all applet 

document.embeds [0] or document.embeds["embedname" in the page///Access all embedded objects in the page 

document.write (); or Document.writeln (); Inserts a string to the location where they are called 

Location objects

Location object: Represents the URL of a loaded window, and can also be used window.location to refer to it 

location.href//The full URL of the currently loaded page, such as Http://www.somewhere.com/pictures The 

protocol used in the/index.htm Location.portocol//url, that is, before the double slash, such as the name of the HTTP 

location.host/server, such as Www.wrox.com 

Location.hostname//is usually equal to the host, sometimes omitting the 

port of the request declared by the previous WWW location.port//url, by default, most URLs do not have port information, such as 8080 

Location.pathname the part of the host name in the//url, such as the 

part after the question mark in the URL of the/pictures/index.htm location.search//Execute GET request, also known as the query string, such as? param= XXXX 

Location.hash//If the URL contains #, return the content after the symbol, such as #anchor1 

location.assign ("http:www.baidu.com"); With Location.href, the new address will be added to the browser's history stack 

location.replace ("http:www.baidu.com");//assign (), but the new address will not be added to the browser's history stack. Cannot access 

Location.reload (True | false) via back and forward;//Reload the current page, when false, overload from the browser cache, or overload from the server side when True, default to False 

Navigator Objects

 ' Navigator ' object: Contains a lot of information about a Web browser, is very useful in detecting browsers and operating systems, and can also be used window.navigator to reference it 

' navigator.appcodename '// A string representing the browser code name 

navigator.appname//Official browser name string representing the 

string representation 

of the Navigator.appversion//browser version information navigator.cookieenabled//If the Enable cookie returns True, returns false 

navigator.javaenabled//returns false 

if Java is enabled to return True Navigator.platform//The string representing the computer platform of the browser is 

Navigator.plugins//installed in the browser in the plugin array 

navigator.taintenabled// Returns true if a data stain is enabled returns false 

Navigator.useragent//The string representation of the user agent header  

Screen Object

 Screen object: Used to get some information about the user's screen, or Window.screen to reference the 

 width and height of its screen.width/height//screens, in pixels 

 screen.availwidth/ availheight//window can use the width and height of the screen, in pixels 

 screen.colordepth//user represents the number of colors, most systems using 32-bit 

 window.moveto (0, 0); 

 Window.resizeto (Screen.availwidth, screen.availheight); Populating the user's screen  

Window Object method

Schematic diagram of BOM and DOM structure


Window Object Mind Mapping

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.