JavaScript » Objects » Ducoment

来源:互联网 发布:mac能玩我的世界吗 编辑:程序博客网 时间:2024/06/03 14:25

The Document object provides access to the elements in an HTML page from within your script. This includes the properties of every form, link and anchor (and, where applicable, any sub-elements), as well as global Document properties such as background and foreground colors.

Properties

alinkColor

Syntax: document.alinkColor = "colorinfo"

This property defines the color of an active link. The "colorinfo" argument is a string that can contain either the hexadecimal definition of the color or it's literal description.

This property defines the color of an active link (defined as after mouse button down, but before mouse button up). The "colorinfo" argument is a string that can contain either the hexadecimal definition of the color or its literal description. If you use the hex definition of a color it must be in the format rrggbb - for example, the hex value for the named color 'forest green' is '228B22'.

Examples

Code:
document.alinkColor = "228B22"
Explanation:

Both lines in this code do exactly the same thing, the first using the hex value of a color and the second using its name.

anchors

Syntax: document.anchors["anchorID" ]

This property is an array containing references to all the named Anchor objects in the current document.

This property is an array containing references to all the named Anchor objects in the current document. These references are stored in the array in the order in which they are defined in the source code. The "anchorID" argument is used to access items in the array and this can either be a string containing the anchor name as defined within the <A></A> tags in the HTML source, or an integer (with '0' being the first item in the array).

Both examples below return the same results; the first uses the defined names of the anchors and the second uses their reference number within the array.

Examples

Code:
// alt 1
document.anchors("anchorname1")
document.anchors("anchorname2")
document.anchors("anchorname3")

// alt 2
document.anchors[0]
document.anchors[1]
document.anchors[2]
Explanation:

Both alternatives in the example return the same results; the first uses the defined names of the anchors and the second uses their reference number within the array.

applets

Syntax: document.applets["appletID"]

This property is an array containing references to all the Applet objects in the current document.

This property is an array containing references to all the named Applet objects in the current document. These references are stored in the array in the order in which they are defined in the source code. The "appletID" argument is used to access items in the array and this can either be a string containing the applet name as defined within the <APPLET> tags in the HTML source, or an integer (with '0' being the first item in the array).

Examples

Code:
document.applets[0]
document.applets[1]
document.applets[2]

document.applets["appletname1"]
document.applets["appletname2"]
document.applets["appletname3"]
Explanation:

Both examples below return the same results; the first uses the defined names of the applets and the second uses their reference number within the array.

bgColor

Syntax: document.bgColor = "colorinfo"

This property defines a document's background color. The "colorinfo" argument is a string that can contain either the hexadecimal definition of the color or it's literal description.

his property defines a document's background color. The "colorinfo" argument is a string that can contain either the hexadecimal definition of the color or its literal description. If you use the hex definition of a color it must be in the format rrggbb - for example, the hex value for the named color 'forest green' is '228B22'.

Examples

Code:
document.bgColor = "228B22"
document.bgColor = "forestgreen"
Explanation:

Both lines in the follwing code do exactly the same thing, the first using the hex value of a color and the second using its name.

constructor

Syntax: Object.constructor

This specifies a function to create an object's property and is inherited by all objects from their prototype.

A constructor property is inherited by all objects from their prototype. It is this fact that allows you to create a new instance of an object using the new operator. If you display the constructor property of any object, you see the construction of the function that created it.

Examples

Code:
document.write(Cat.constructor)
Output:
function Cat(breed, name, age) { this.breed = breed this.name = name
this.age = age }
Explanation:

Assuming the existence of an object called 'Cat', this code would display that function.

Code:
if(Sheeba.constructor == Cat)
   document.write("This is an instance of 'Cat'.")
Explanation:

The constructor property can also be used to compare two objects (including those, such as documents and forms, that cannot be constructed). This example compares the 'Sheeba' object with the 'Cat' object to see if it is an instance of it.

cookie

Syntax: document.cookie[ = "expression(s)"]

This property is a string that returns a report detailing all visible and un-expired cookies that are associated with the specified document.

this property is a string that returns a report detailing all visible and un-expired cookies that are associated with the specified document. The value returned using this method only contains the name and value attributes of the associated cookies in a single string.

When setting the cookie property, which can be done at any time, the following syntax must be used:

"name" = "value"; expires = "date"; path = "directory"; domain = "domainName"; secure

The "date" parameter must be in the format as returned by the toGMTString() method of the Date object. The expires attribute is optional; not setting this will mean that the cookie will expire when the user shuts down their browser. If set, the cookie survives until the set expiry date. "domainName" sets the cookie's visibility to a particular domain although this attribute is rarely used as it defaults to the domain of the carrying document and visibility of the cookie is normally restricted to this document alone. The path parameter is similar to domain in that it restricts the cookie's visibilty to the specified directory on the web server. The secure attribute is less commonly used. It is a Boolean (true or false) that, when true, suggests that the browser should only make secure (SSL) URL requests when the cookie is sent to the server.

Examples

Code:
document.write(document.cookie)
Output:
usr_id=13455; bookmark=products.html
domain

Syntax: document.domain = "domaininfo"

This property sets or returns the domain name of the server from which the document originated.

his property sets or returns the domain name of the server from which the document originated. This defaults to the domain name of the server that the document was retreived from, but can be changed to a suffix (and only a suffix) of this name. This allows the sharing of script properties, security allowing, between documents delivered from different servers providing they share the same domain suffix.

The way you can alter the domain name property is very limited. For example, if a document was retreived from the URL 'search.devguru.com', you could change the domain property to 'devguru.com' but not 'search.devguru'.

Examples

Code:
document.domain = "devguru.com"     // This example is o.k.

document.domain = "search.devguru"     // This example is not allowed

document.domain = "devguru.net"     // This example is not allowed
Explanation:

These examples relate to a document retreived from the URL 'search.devguru.com'

embeds

Syntax: document.embeds["embed_objID" ]

This property is an array containing references to all the embedded objects in the current document.

This property is an array containing references to all the embedded objects in the current document. These references are stored in the array in the order in which they are defined in the source code. The "embed_objID" argument is used to access items in the array and this can either be a string containing the embedded object's name as defined within the <EMBED> tag in the HTML source, or an integer (with '0' being the first item in the array).

Examples

Code:
document.embeds["embed_obj1"]
document.embeds["embed_obj2"]
document.embeds["embed_obj3"]

document.embeds[0]
document.embeds[1]
document.embeds[2]
Explanation:

Both examples return the same results; the first uses the defined names of the embedded objects and the second uses their reference number within the array.

fgColor

Syntax: document.fgColor = "colorinfo"

This property defines a document's foreground (text) color. The "colorinfo" argument is a string that can contain either the hexadecimal definition of the color or it's literal description.

This property defines a document's foreground (text) color. The "colorinfo" argument is a string that can contain either the hexadecimal definition of the color or its literal description. If you use the hex definition of a color it must be in the format rrggbb - for example, the hex value for the named color 'forest green' is '228B22'.

Examples

Code:
document.fgColor = "228B22"
document.fgColor = "forestgreen"
Explanation:

Both lines in the follwing code do exactly the same thing, the first using the hex value of a color and the second using its name.

formName

Syntax: document."formname"

Every form in a document has a separate document object property, the name of which is taken from the value asigned to the form with the <FORM NAME = "formID"> tag. Any form in the document can then be referred to with the syntax below.

forms

Syntax: document.forms["formID" ]

This property is an array containing references to all the Form objects in the current document.

This property is an array containing references to all the Form objects in the current document. These references are stored in the array in the order in which they are defined in the source code. The "formID" argument is used to access items in the array and this can either be a string containing the form name as defined within the <FORM> tag in the HTML source, or an integer (with '0' being the first item in the array).

Examples

Code:
document.forms["formname1"]
document.forms["formname2"]
document.forms["formname3"]

document.forms[0]
document.forms[1]
document.forms[2]

document.formname1
document.formname2
document.formname3
Explanation:

All examples return the same results; the first uses the defined names of the forms and the second uses their reference number within the array. A separate property is assigned to the document object for each form, which means that the forms can be accessed as in the last example.

images

Syntax: document.images["imageID"]

This property is an array containing references to all the Image objects in the current document.

This property is an array containing references to all the Image objects in the current document. These references are stored in the array in the order in which they are defined in the source code. The "imageID" argument is used to access items in the array and this can either be a string containing the image name as defined within the <IMG> tag in the HTML source, or an integer (with '0' being the first item in the array).

Examples

Code:
document.images["imagename1"]
document.images["imagename2"]
document.images["imagename3"]

document.images[0]
document.images[1]
document.images[2]
Explanation:

Both examples return the same results; the first uses the defined names of the images and the second uses their reference number within the array.

lastModified

Syntax: document.lastModified

This property returns the date that the document was last modified.

This property returns a string relating to the date that the document was last modified, which is usually, but not always, contained in the HTTP header of a document. When this data is supplied, the server from which the document originated interogates the file for its 'last modified' date and includes this in the header information of the document. If a particular server doesn't do this, and no 'date last modified' data exists in the HTTP header, JavaScript will return a value of '0', which it interprets as 'Janurary 1, 1970 GMT'

Examples

Code:
datelastmod = document.lastModified
document.write("This document was last modified on " + datelastmod)
Output:
"This document was last modified on 10/28/97 12/06/56"
Explanation:

This example gets the last modified date of a document and displays it in the browser.

layers

Syntax: document.layers["layerID"]

This property is an array containing references to all the Layer objects in the current document.

This property is an array containing references to all the Layer objects in the current document. These references are stored in the array in the order in which they are defined in the source code. The "layerID" argument is used to access items in the array and this can either be a string containing the layer name as defined within the <LAYER> or <ILAYER> tag in the HTML source, or an integer (with '0' being the first item in the array).

Note that when accessing the layers by their reference integer, as opposed to name, they are stored in the array in z-order (from back to front, with the back-most layer indexed as '0').

Examples

Code:
document.layers["layername1"]
document.layers["layername2"]
document.layers["layername3"]

document.layers[0]
document.layers[1]
document.layers[2]
Explanation:

Note that when accessing the layers by their reference integer, as opposed to name, they are stored in the array in z-order (from back to front, with the back-most layer indexed as '0').

linkColor

Syntax: document.linkColor = "colorinfo"

This property defines the color of any hyperlinks in the document. The "colorinfo" argument is a string that can contain either the hexadecimal definition of the color or it's literal description.

This property defines the color of any hyperlinks in the document. The "colorinfo" argument is a string that can contain either the hexadecimal definition of the color or its literal description. If you use the hex definition of a color it must be in the format rrggbb - for example, the hex value for the named color 'forest green' is '228B22'.

Examples

Code:
document.linkColor = "228B22"
document.linkColor = "forestgreen"
Explanation:

Both lines in the code do exactly the same thing, the first using the hex value of a color and the second using its name.

links

Syntax: document.links["linkID"]

This property is an array containing references to all the Area and Link objects in the current document.

This property is an array containing references to all the Area and Link objects in the current document. These references are stored in the array in the order in which they are defined in the source source code. The "linkID" argument is an integer relating to a link defined within a <A HREF = " "> or <AREA HREF = " "> tag in the HTML source.

Examples

Code:
document.links[0]
document.links[1]
document.links[2]
plugins

Syntax: document.plugins["pluginID"]

This property is an array containing references to all the Plugin objects in the current document.

This property is an array containing references to all the Plugin objects in the current document. These references are stored in the array in the order in which they are defined in the source code, and are accessed using the "pluginID" argument, which is an integer with the first plugin object being '0'.

Examples

Code:
document.plugins[0]
document.plugins[1]
document.plugins[2]
prototype

Syntax: Object.prototype.name = value

This allows the addition of properties and methods to any object.

Any object that can call a constructor function has a prototype property allowing the addition of properties and methods.

Examples

Code:
Cat.prototype.color = null
Sheeba.color = "black"
Explanation:

This example first creates a 'color' property for the 'Cat' object, and then creates a specific instance of it.

referrer

Syntax: document.referrer

If a destination document is reached by a user clicking on a Link object in another document (the referrer), this property returns the referring document's URL.

title

Syntax: document.title

This property returns the document's name as defined between the <TITLE></TITLE> tags.

URL

Syntax: document.URL

This property is used to retrieve the document's full URL.

vlinkColor

Syntax: document.vlinkColor = "colorinfo"

This property defines the color of any visited links in the document. The "colorinfo" argument is a string that can contain either the hexadecimal definition of the color or it's literal description.

This property defines the color of any visited links in the document. The "colorinfo" argument is a string that can contain either the hexadecimal definition of the color or its literal description. If you use the hex definition of a color it must be in the format rrggbb - for example, the hex value for the named color 'forest green' is '228B22'.

Examples

Code:
document.linkColor = "228B22"
document.linkColor = "forestgreen"
Explanation:

Both lines in the code do exactly the same thing, the first using the hex value of a color and the second using its name.

Methods

captureEvents

Syntax: document.captureEvents(eventType)

This method instructs the document to capture and handle all events of a particular type. See the event object for a list of event types.

close

Syntax: document.close( )

This method closes an output stream previously opened with the document.open method and forces data collected from any instances of the document.write or document.writeln methods to be displayed.

This method closes an output stream previously opened with the document.open method and forces data collected from any instances of the document.write or document.writeln methods to be displayed.

Examples

Code:
function newWindowTest() {
  var message1 = "Hello, world!"
  var message2 = "This is a test."
  newWindow.document.open("text/html", "replace")
  newWindow.document.writeln("message1)
  newWindow.document.write("message2)
  newWindow.document.close()
}

newWindow=window.open('','','toolbar=no,scrollbars=no,width=200,height=150')
newWindowTest()
Output:
"Hello, world! This is a test."
Explanation:

This example demonstrates this and displays the output stream in a new window.

eval

Syntax: Object.eval(string)

The eval method is deprecated as a method of Object, but is still used as a high level function. It evaluates a string of JavaScript in the context of an object.

getElementById

Syntax: document.getElementById(id)

This element receives a string containing the id of a specific element and returns a reference to it.

After obtaining a reference to the object, you can use the getAttribute and setAttribute methods to modify the element's attributes.

Examples

Code:
<p id="myID" attr="my attribute value">

...

<script>
  var pTag1 = document.getElementById('myID');
  document.write(pTag1.getAttribute('attr') + '<br>/n');
  pTag1.setAttribute('attr', 'my new attribute value');
  document.write(pTag1.getAttribute('attr'));
</script>
Output:
my attribute value
my new attribute value
Language(s): HTML JavaScript
getSelection

Syntax: document.getSelection( )

This method can be used to return the contents of selected text in the current document.

This method can be used to return a string containing any selected text in the current document.

Examples

Code:
<INPUT TYPE="BUTTON" NAME="selectString" VALUE="Show
any highlighted text" onClick="alert('The following text is
selected:/n'+document.getSelection());">
handleEvent

Syntax: document.handleEvent(event)

This method calls the handler for the specified event.

open

Syntax: document.open([mimeType[, replace]])

This method is used to open a stream to collect the output from any write or writeln methods.

This method is used to open a stream to collect the output from any write or writeln methods. The first of the optional parameters is mimeType which determines the type of document you are writing to; if this parameter is not used, the default value is "text/html". The second parameter is replace, also optional, which causes the history entry for the new document to inherit the history entry from the document from which it was opened.

Examples

Code:
function newWindowTest() {
  var message1 = "Hello, world!"
  var message2 = "This is a test."
  newWindow.document.open("text/html", "replace")
  newWindow.document.writeln(message1)
  newWindow.document.write(message2)
  newWindow.document.close()
}

newWindow=window.open('','','toolbar=no,scrollbars=no,width=200,height=150')
newWindowTest()
Output:
"Hello, world! This is a test."
Explanation:

The following code demonstrates this method and displays the output stream in a new window.

releaseEvents

Syntax: document.releaseEvents(eventType)

This method is used to set the document to release any events of the type eventType and passes them along to objects further down the event heirarchy.

routeEvent

Syntax: document.routeEvent(event)

This method is used to send the event specified along the normal event hierarchy.

toSource

Syntax: Object.toSource()

The toSource method returns a literal representing the source code of an object. This can then be used to create a new object.

The toSource method returns a literal representing the source code of an object. This can then be used to create a new object. Although the toSource method is usually called by JavaScript behind the scenes, you can call it yourself. In the case of the built-in Object object, it returns a string indicating that the source code is not available, while, for instances of Object, it returns the source. With a user-defined object, toSource will return the JavaScript source that defines it.

Examples

Code:
Object.toSource()
Output:
function Object() { [native code] }
Code:
function Cat(breed, name, age)
{
   this.breed = breed
   this.name = name
   this.age = age
}
Cat.toSource()
Output:
function Cat(breed, name, age) { this.breed = breed; this.name = name; this.age = age; }
Code:
Sheeba = new Cat("Manx", "Felix", 7)
Sheeba.toSource()
Output:
{breed:"Manx", name:"Felix", age:7}
toString

Syntax: Object.toString()

The toString method returns a string representing a specified object.

The toString method is inherited by every object descended from Object and returns a string representing a specified object. There are times when an object needs to be represented as a string, and the toString method (which comes with every object) is automatically called to do that. ToString returns the object type or the constructor function that created it.
 
The toString method can, however, be overwritten in a custom object by assigning a user-defined function in its place as follows:

NOTE:
 
Every core JavaScript object will over-ride the toString method to return an appropriate value, and will only call it when it needs to convert an object to a string.

Examples

Code:
Cat.prototype.toString = myToString
Explanation:

The toString method can be overwritten in a custom object by assigning a user-defined function in its place.

Code:
document.write(Sheeba)
Output:
[object Object]
Code:
document.write(Sheeba.toString)
Output:
function toString() { [native code] }
unwatch

Syntax: Object.unwatch(property)

This method removes a watchpoint set for an object and property name with the watch method.

valueOf

Syntax: Object.valueOf()

This method returns a primitive value for a specified object.

The valueOf method returns a primitive value for a specified object and is inherited by all objects descended from Object. It is usually called automatically by JavaScript behind the scenes whenever it encounters an object where a primitive value is expected. If the object has no primitive value, then the object itself is returned as [object Object]. You can also call valueOf yourself to convert a built-in object into a primitive value.

NOTE:
 
Every core JavaScript object will over-ride the valueOf method to return an appropriate value.

Examples

Code:
(Object.valueOf()
Output:
function Object() { [native code] }
Code:
Cat.prototype.valueOf() = myValueOf()
Explanation:

The valueOf method can also be overwritten in a custom object by assigning a user-defined function with no arguments in its place.

Code:
function Cat(breed, name, age)
{
   this.breed = breed
   this.name = name
}
Cat.valueOf()
Output:
function Cat(breed, name, age) { this.breed = breed this.name = name }
watch

Syntax: Object.watch(property, handlerfunction)

This method adds a watchpoint to a property of the object.

The watch method is inherited by every object descended from Object and adds a watchpoint to a property of the method. Whenever a value is assigned to it, it calls up a function allowing you to watch any new value assigned and, if necessary, alter it.

NOTE:
 
A watchpoint for a property does not disappear if that property is deleted. It can, however, be removed by using the unwatch method.

Examples

Code:
city = {name:"Chicago"}
city.watch("name", myfunction (property, oldval, newval)
                                    {
                                       if(newval == "Leningrad")
                                          newval = "St. Petersburg"
                                       return newval
                                    }
                ) //end of watch method
Explanation:

This following code watches the 'name' property of the 'city' object, and if the name 'Leningrad' is assigned to it, it is altered to the city's new name of 'St. Petersburg'. Note the code that is enclosed in the pair of curly braces (an if statement) which is associated with the handlerfunction argument called 'myfunction':

write

Syntax: document.write("expression1", [expression2, [...]])

This method is used to write HTML expressions to the specified document.

This method is used to write HTML expressions and JavaScript code to the specified document in a current or new window.

Multiple arguments, ("expression1", [expression2, [...]]), can be listed and they will be appended to the document in order of occurrence. They can be of any type supported by JavaScript (string, numeric, logical), but all non-string expressions will be converted to a string before being appended.

In general, it is not necessary to open the document using the document.open method, since the document.write method will automatically open the file and discard (erase) the contents. However, after the write is complete, you need to close the document by using the document.close method. In some browsers, the results of the write may not be completely displayed, due to buffering, until the close occurs.

Examples

Code:
newWindow = window.open('', 'newWin')
var tagBoldOpen = "<b>"
var tagBoldClose = "</b>"
newWindow.document.write(tagBoldOpen)
newWindow.document.write("This is some bold text.", tagBoldClose)
newWindow.document.close()
writeln

Syntax: document.writeln("expression(s)")

This method is identical to the write method detailed above, with the addition of writing a new line character after any specified expressions.

 
原创粉丝点击