JavaScript手册 
目录
此参考中包含
的内容
轻松上手
简介
操作符
语句
核心
文档
窗口
表单
浏览器
事件和
事件句柄
LiveWire
数据库服务
进程管理服务
实用工具
全局函数
LiveConnect
的Java包
索引
版权
 
【目录】 【上一页】 【下一页】 【索引】

document

Contains information about the current document, and provides methods for displaying HTML output to the user.

客户端对象
实现版本Navigator 2.0
Navigator 3.0: 添加了 onBlur and onFocus语法; 添加了 applets, domain, embeds, forms, formName, images, and plugins properties.
Navigator 4.0: 添加了 layers 属性; 添加了 captureEvents, getSelection, handleEvent, releaseEvents, and routeEvent 方法s.

创建源

The HTML BODY tag. The JavaScript runtime engine creates a document object for each HTML page. Each Window object has a document property whose value is a document object.

To define a document object, use standard HTML语法 for the BODY tag with the addition of JavaScript event handlers.

事件句柄

The onBlur, onFocus, onLoad, and onUnload event handlers are specified in the BODY tag but are actually event handlers for the Window object. The following are event handlers for the document object.

描述

An HTML document consists of HEAD and BODY tags. The HEAD tag includes information on the document's title and base (the absolute URL base to be used for relative URL links in the document). The BODY tag encloses the body of a document, which is defined by the current URL. The entire body of the document (all other HTML elements for the document) goes within the BODY tag.

You can load a new document by setting the Window.location property.

You can clear the document pane (and remove the text, form elements, and so on so they do not redisplay) with these statements:

document.close();
document.open();
document.write();
You can omit the document.open call if you are writing text or HTML, since write does an implicit open of that MIME type if the document stream is closed.

You can refer to the anchors, forms, and links of a document by using the anchors, forms, and links arrays. These arrays contain an entry for each anchor, form, or link in a document and are properties of the document object.

Do not use location as a property of the document object; use the document.URL property instead. The document.location property, which is a synonym for document.URL, will be removed in a future release.

属性概览

alinkColorA string that specifies the ALINK attribute.
anchorsAn array containing an entry for each anchor in the document.
appletsAn array containing an entry for each applet in the document.
bgColorA string that specifies the BGCOLOR attribute.
cookieSpecifies a cookie.
domainSpecifies the domain name of the server that served a document.
embedsAn array containing an entry for each plug-in in the document.
fgColorA string that specifies the TEXT attribute.
formNameA separate 属性 for each named form in the document.
formsAn array a containing an entry for each form in the document.
imagesAn array containing an entry for each image in the document.
lastModifiedA string that specifies the date the document was last modified.
layersArray containing an entry for each layer within the document.
linkColorA string that specifies the LINK attribute.
linksAn array containing an entry for each link in the document.
pluginsAn array containing an entry for each plug-in in the document.
referrerA string that specifies the URL of the calling document.
titleA string that specifies the contents of the TITLE tag.
URLA string that specifies the complete URL of a document.
vlinkColorA string that specifies the VLINK attribute.

方法概览

captureEventsSets the document to capture all events of the specified type.
closeCloses an output stream and forces data to display.
getSelectionReturns a string containing the text of the current selection.
handleEvent调用指定事件的控制句柄。
openOpens a stream to collect the output of write or writeln 方法s.
releaseEventsSets the window or document to release captured events of thespecified type, sending the event to objects further along the event hierarchy.
routeEventPasses a captured event along the normal event hierarchy.
writeWrites one or more HTML expressions to a document in the specified window.
writelnWrites one or more HTML expressions to a document in the specified window and follows them with a newline character.

示例

The following example creates two frames, each with one document. The document in the first frame contains links to anchors in the document of the second frame. Each document defines its colors.

doc0.html, which defines the frames, contains the following code:

<HTML>
<HEAD>
<TITLE>Document object example</TITLE>
</HEAD>
<FRAMESET COLS="30%,70%">
<FRAME SRC="doc1.html" NAME="frame1">
<FRAME SRC="doc2.html" NAME="frame2">
</FRAMESET>
</HTML>
doc1.html, which defines the content for the first frame, contains the following code:

<HTML>
<SCRIPT>
</SCRIPT>
<BODY
   BGCOLOR="antiquewhite"
   TEXT="darkviolet"
   LINK="fuchsia"
   ALINK="forestgreen"
   VLINK="navy">
<P><B>Some links</B>
<LI><A HREF="doc2.html#numbers" TARGET="frame2">Numbers</A>
<LI><A HREF="doc2.html#colors" TARGET="frame2">Colors</A>
<LI><A HREF="doc2.html#musicTypes" TARGET="frame2">Music types</A>
<LI><A HREF="doc2.html#countries" TARGET="frame2">Countries</A>
</BODY>
</HTML>
doc2.html, which defines the content for the second frame, contains the following code:

<HTML>
<SCRIPT>
</SCRIPT>
<BODY
   BGCOLOR="oldlace" onLoad="alert('Hello, World.')"
   TEXT="navy">
<P><A NAME="numbers"><B>Some numbers</B></A>
<UL><LI>one
<LI>two
<LI>three
<LI>four</UL>
<P><A NAME="colors"><B>Some colors</B></A>
<UL><LI>red
<LI>orange
<LI>yellow
<LI>green</UL>
<P><A NAME="musicTypes"><B>Some music types</B></A>
<UL><LI>R&B
<LI>Jazz
<LI>Soul
<LI>Reggae</UL>
<P><A NAME="countries"><B>Some countries</B></A>
<UL><LI>Afghanistan
<LI>Brazil
<LI>Canada
<LI>Finland</UL>
</BODY>
</HTML>

参看

Frame, Window

属性

alinkColor

A string specifying the color of an active link (after mouse-button down, but before mouse-button up).

属性源document
实现版本Navigator 2.0

描述

The alinkColor property is expressed as a hexadecimal RGB triplet or as one of the string literals listed in Appendix B, "Color Values," in the JavaScript Guide This property is the JavaScript reflection of the ALINK attribute of the BODY tag. You cannot set this property after the HTML source has been through layout.

If you express the color as a hexadecimal RGB triplet, you must use the format rrggbb. For example, the hexadecimal RGB values for salmon are red=FA, green=80, and blue=72, so the RGB triplet for salmon is "FA8072".

示例

The following example sets the color of active links using a string literal:

document.alinkColor="aqua" The following example sets the color of active links to aqua using a hexadecimal triplet:

document.alinkColor="00FFFF"

参看

document.bgColor, document.fgColor, document.linkColor, document.vlinkColor

anchors

An array of objects corresponding to named anchors in source order.

属性源document
只读
实现版本Navigator 2.0

描述

You can refer to the Anchor objects in your code by using the anchors array. This array contains an entry for each A tag containing a NAME attribute in a document; these entries are in source order. For example, if a document contains three named anchors whose NAME attributes are anchor1, anchor2, and anchor3, you can refer to the anchors either as:

document.anchors["anchor1"]
document.anchors["anchor2"]
document.anchors["anchor3"]
or as:

document.anchors[0]
document.anchors[1]
document.anchors[2]
To obtain the number of anchors in a document, use the length property: document.anchors.length. If a document names anchors in a systematic way using natural numbers, you can use the anchors array and its length property to validate an anchor name before using it in operations such as setting location.hash.

applets

An array of objects corresponding to the applets in a document in source order.

属性源document
只读
实现版本Navigator 3.0

描述

You can refer to the applets in your code by using the applets array. This array contains an entry for each Applet object (APPLET tag) in a document; these entries are in source order. For example, if a document contains three applets whose NAME attributes are app1, app2, and app3, you can refer to the anchors either as:

document.applets["app1"]
document.applets["app2"]
document.applets["app3"]
or as:

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

bgColor

A string specifying the color of the document background.

属性源document
实现版本Navigator 2.0

描述

The bgColor property is expressed as a hexadecimal RGB triplet or as one of the string literals listed in Appendix B, "Color Values," in the JavaScript Guide. This property is the JavaScript reflection of the BGCOLOR attribute of the BODY tag. The default value of this property is set by the user with the preferences dialog box.

If you express the color as a hexadecimal RGB triplet, you must use the format rrggbb. For example, the hexadecimal RGB values for salmon are red=FA, green=80, and blue=72, so the RGB triplet for salmon is "FA8072".

示例

The following example sets the color of the document background to aqua using a string literal:

document.bgColor="aqua" The following example sets the color of the document background to aqua using a hexadecimal triplet:

document.bgColor="00FFFF"

参看

document.alinkColor, document.fgColor, document.linkColor, document.vlinkColor

cookie

String value representing all of the cookies associated with this document.

属性源document
实现版本Navigator 2.0

安全性

Navigator 3.0:该属性默认是带有污点的。有关数据污点的更多信息,请看“JavaScript 的安全性”

描述

A cookie is a small piece of information stored by the web browser in the cookies.txt file. Use string methods such as substring, charAt, indexOf, and lastIndexOf to determine the value stored in the cookie. See the JavaScript Guide for a complete specification of the cookie语法.

You can set the cookie property at any time.

The "expires=" component in the cookie file sets an expiration date for the cookie, so it persists beyond the current browser session. This date string is formatted as follows:

Wdy, DD-Mon-YY HH:MM:SS GMT This format represents the following values:

For example, a valid cookie expiration date is

expires=Wednesday, 09-Nov-99 23:12:40 GMT The cookie date format is the same as the date returned by toGMTString, with the following exceptions:

示例

The following function uses the cookie property to record a reminder for users of an application. The cookie expiration date is set to one day after the date of the reminder.

function RecordReminder(time, expression) {
   // Record a cookie of the form "@<T>=<E>" to map
   // from <T> in milliseconds since the epoch,
   // returned by Date.getTime(), onto an encoded expression,
   // <E> (encoded to contain no white space, semicolon,
   // or comma characters)
   document.cookie = "@" + time + "=" + expression + ";"
   // set the cookie expiration time to one day
   // beyond the reminder time
   document.cookie += "expires=" + cookieDate(time + 24*60*60*1000)
   // cookieDate is a function that formats the date
   //according to the cookie spec
}

参看

Hidden

domain

Specifies the domain name of the server that served a document.

属性源document
实现版本Navigator 3.0

安全性

Navigator 3.0:该属性默认是带有污点的。有关数据污点的更多信息,请看“JavaScript 的安全性”

描述

Navigator 3.0: The domain property lets scripts on multiple servers share properties when data tainting is not enabled. With tainting disabled, a script running in one window can read properties of another window only if both windows come from the same Web server. But large Web sites with multiple servers might need to share properties among servers. For example, a script on the host www.royalairways.com might need to share properties with a script on the host search.royalairways.com.

If scripts on two different servers change their domain property so that both scripts have the same domain name, both scripts can share properties. For example, a script loaded from search.royalairways.com could set its domain property to "royalairways.com". A script from www.royalairways.com running in another window could also set its domain property to "royalairways.com". Then, since both scripts have the domain "royalairways.com", these two scripts can share properties, even though they did not originate from the same server.

You can change domain only in a restricted way. Initially, domain contains the hostname of the Web server from which the document was loaded. You can set domain only to a domain suffix of itself. For example, a script from search.royalairways.com can't set its domain property to "search.royalairways". And a script from IWantYourMoney.com cannot set its domain to "royalairways.com".

Once you change the domain property, you cannot change it back to its original value. For example, if you change domain from "search.royalairways.com" to "royalairways.com", you cannot reset it to "search.royalairways.com".

示例

The following statement changes the domain property to "braveNewWorld.com". This statement is valid only if "braveNewWorld.com" is a suffix of the current domain, such as "www.braveNewWorld.com".

document.domain="braveNewWorld.com"

embeds

An array containing an entry for each object embedded in the document.

属性源document
只读
实现版本Navigator 3.0

描述

You can refer to embedded objects (created with the EMBED tag) in your code by using the embeds array. This array contains an entry for each EMBED tag in a document in source order. For example, if a document contains three embedded objects whose NAME attributes are e1, e2, and e3, you can refer to the objects either as:

document.embeds["e1"]
document.embeds["e2"]
document.embeds["e3"]
or as:

document.embeds[0]
document.embeds[1]
document.embeds[2]
Elements in the embeds array may have public callable functions, if they refer to a plug-in that uses LiveConnect. See the JavaScript Guide.

Use the elements in the embeds array to interact with the plug-in that is displaying the embedded object. If a plug-in is not Java-enabled, you cannot do anything with its element in the embeds array. The fields and methods of the elements in the embeds array vary from plug-in to plug-in; see the documentation supplied by the plug-in manufacturer.

When you use the EMBED tag to generate output from a plug-in application, you are not creating a Plugin object.

示例

The following code includes an audio plug-in in a document.

<EMBED SRC="train.au" HEIGHT=50 WIDTH=250>

参看

Plugin

fgColor

A string specifying the color of the document (foreground) text.

属性源document
实现版本Navigator 2.0

描述

The fgColor property is expressed as a hexadecimal RGB triplet or as one of the string literals listed in Appendix B, "Color Values," in the JavaScript Guide. This property is the JavaScript reflection of the TEXT attribute of the BODY tag. The default value of this property is set by the user with the preferences dialog box You cannot set this property after the HTML source has been through layout.

If you express the color as a hexadecimal RGB triplet, you must use the format rrggbb. For example, the hexadecimal RGB values for salmon are red=FA, green=80, and blue=72, so the RGB triplet for salmon is "FA8072".

You can override the value set in the fgColor property in either of the following ways:

formName

属性源document
实现版本Navigator 3.0

The document object contains a separate property for each form in the document. The name of this property is the value of its NAME attribute. See Form for information on Form objects. You cannot add new forms to the document by creating new properties, but you can modify the form by modifying this object.

forms

An array containing an entry for each form in the document.

属性源document
只读
实现版本Navigator 3.0

安全性

Navigator 3.0:该属性默认是带有污点的。有关数据污点的更多信息,请看“JavaScript 的安全性”

描述

You can refer to the forms in your code by using the forms array (you can also use the form name). This array contains an entry for each Form object (FORM tag) in a document; these entries are in source order. For example, if a document contains three forms whose NAME attributes are form1, form2, and form3, you can refer to the objects in the forms array either as:

document.forms["form1"]
document.forms["form2"]
document.forms["form3"]
or as:

document.forms[0]
document.forms[1]
document.forms[2]
Additionally, the document object has a separate property for each named form, so you could refer to these forms also as:

document.form1
document.form2
document.form3
For example, you would refer to a Text object named quantity in the second form as document.forms[1].quantity. You would refer to the value property of this Text object as document.forms[1].quantity.value.

The value of each element in the forms array is <object nameAttribute>, where nameAttribute is the NAME attribute of the form.

images

An array containing an entry for each image in the document.

属性源document
只读
实现版本Navigator 3.0

You can refer to the images in a document by using the images array. This array contains an entry for each Image object (IMG tag) in a document; the entries are in source order. Images created with the Image constructor are not included in the images array. For example, if a document contains three images whose NAME attributes are im1, im2, and im3, you can refer to the objects in the images array either as:

document.images["im1"]
document.images["im2"]
document.images["im3"]
or as:

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

lastModified

A string representing the date that a document was last modified.

属性源document
只读
实现版本Navigator 2.0

安全性

Navigator 3.0:该属性默认是带有污点的。有关数据污点的更多信息,请看“JavaScript 的安全性”

描述

The lastModified property is derived from the HTTP header data sent by the web server. Servers generally obtain this date by examining the file's modification date.

The last modified date is not a required portion of the header, and some servers do not supply it. If the server does not return the last modified information, JavaScript receives a 0, which it displays as January 1, 1970 GMT. The following code checks the date returned by lastModified and prints out a value that corresponds to unknown.

lastmod = document.lastModified // get string of last modified date
lastmoddate = Date.parse(lastmod)   // convert modified string to date
if(lastmoddate == 0){               // unknown date (or January 1, 1970 GMT)
   document.writeln("Lastmodified: Unknown")
   } else {
   document.writeln("LastModified: " + lastmod)
}

示例

In the following example, the lastModified property is used in a SCRIPT tag at the end of an HTML file to display the modification date of the page:

document.write("This page updated on " + document.lastModified)

layers

The layers property is an array containing an entry for each layer within the document.

属性源document
实现版本Navigator 4.0

描述

You can refer to the layers in your code by using the layers array. This array contains an entry for each Layer object (LAYER or ILAYER tag) in a document; these entries are in source order. For example, if a document contains three layers whose NAME attributes are layer1, layer2, and layer3, you can refer to the objects in the layers array either as:

document.layers["layer1"]
document.layers["layer2"]
document.layers["layer3"]
or as:

document.layers[0]
document.layers[1]
document.layers[2]
When accessed by integer index, array elements appear in z-order from back to front, where 0 is the bottommost layer and higher layers are indexed by consecutive integers. The index of a layer is not the same as its zIndex property, as the latter does not necessarily enumerate layers with consecutive integers. Adjacent layers can have the same zIndex property values.

These are valid ways of accessing layer objects:

document.layerName
document.layers【索引】
document.layers["layerName"]
// example of using layers property to access nested layers:
document.layers["parentlayer"].layers["childlayer"]
Elements of a layers array are JavaScript objects that cannot be set by assignment, though their properties can be set. For example, the statement

document.layers[0]="music" is invalid (and ignored) because it attempts to alter the layers array. However, the properties of the objects in the array readable and some are wri表. For example, the statement

document.layers["suspect1"].left = 100; is valid. This sets the layer's horizontal position to 100. The following example sets the background color to blue for the layer bluehouse which is nested in the layer houses.

document.layers["houses"].layers["bluehouse"].bgColor="blue";

linkColor

A string specifying the color of the document hyperlinks.

属性源document
实现版本Navigator 2.0

描述

The linkColor property is expressed as a hexadecimal RGB triplet or as one of the string literals listed in the JavaScript Guide. This property is the JavaScript reflection of the LINK attribute of the BODY tag. The default value of this property is set by the user with the preferences dialog box. You cannot set this property after the HTML source has been through layout.

If you express the color as a hexadecimal RGB triplet, you must use the format rrggbb. For example, the hexadecimal RGB values for salmon are red=FA, green=80, and blue=72, so the RGB triplet for salmon is "FA8072".

示例

The following example sets the color of document links to aqua using a string literal:

document.linkColor="aqua" The following example sets the color of document links to aqua using a hexadecimal triplet:

document.linkColor="00FFFF"

参看

document.alinkColor, document.bgColor, document.fgColor, document.vlinkColor

links

An array of objects corresponding to Area and Link objects in source order.

属性源document
只读
实现版本Navigator 2.0

安全性

Navigator 3.0:该属性默认是带有污点的。有关数据污点的更多信息,请看“JavaScript 的安全性”

描述

You can refer to the Area and Link objects in your code by using the links array. This array contains an entry for each Area (<AREA HREF="..."> tag) and Link (<A HREF="..."> tag) object in a document in source order. It also contains links created with the link method. For example, if a document contains three links, you can refer to them as:

document.links[0]
document.links[1]
document.links[2]

plugins

An array of objects corresponding to Plugin objects in source order.

属性源document
只读
实现版本Navigator 3.0

You can refer to the Plugin objects in your code by using the plugins array. This array contains an entry for each Plugin object in a document in source order. For example, if a document contains three plugins, you can refer to them as:

document.plugins[0]
document.plugins[1]
document.plugins[2]

referrer

Specifies the URL of the calling document when a user clicks a link.

属性源document
只读
实现版本Navigator 2.0

安全性

Navigator 3.0:该属性默认是带有污点的。有关数据污点的更多信息,请看“JavaScript 的安全性”

描述

When a user navigates to a destination document by clicking a Link object on a source document, the referrer property contains the URL of the source document.

referrer is empty if the user typed a URL in the Location box, or used some other means to get to the current URL. referrer is also empty if the server does not provide environment variable information.

示例

In the following example, the getReferrer function is called from the destination document. It returns the URL of the source document.

function getReferrer() {
   return document.referrer
}

title

A string representing the title of a document.

属性源document
只读
实现版本Navigator 2.0

安全性

Navigator 3.0:该属性默认是带有污点的。有关数据污点的更多信息,请看“JavaScript 的安全性”

描述

The title property is a reflection of the value specified between the TITLE start and end tags. If a document does not have a title, the title property is null.

示例

In the following example, the value of the title property is assigned to a variable called docTitle:

var newWindow = window.open("http://home.netscape.com")
var docTitle = newWindow.document.title

URL

A string specifying the complete URL of the document.

属性源document
只读
实现版本Navigator 2.0

安全性

Navigator 3.0:该属性默认是带有污点的。有关数据污点的更多信息,请看“JavaScript 的安全性”

描述

URL is a string-valued property containing the full URL of the document. It usually matches what window.location.href is set to when you load the document, but redirection may change location.href.

示例

The following example displays the URL of the current document:

document.write("The current URL is " + document.URL)

参看

Location.href

vlinkColor

A string specifying the color of visited links.

属性源document
实现版本Navigator 2.0

描述

The vlinkColor property is expressed as a hexadecimal RGB triplet or as one of the string literals listed in the JavaScript Guide. This property is the JavaScript reflection of the VLINK attribute of the BODY tag. The default value of this property is set by the user with the preferences dialog box. You cannot set this property after the HTML source has been through layout.

If you express the color as a hexadecimal RGB triplet, you must use the format rrggbb. For example, the hexadecimal RGB values for salmon are red=FA, green=80, and blue=72, so the RGB triplet for salmon is "FA8072".

示例

The following example sets the color of visited links to aqua using a string literal:

document.vlinkColor="aqua" The following example sets the color of active links to aqua using a hexadecimal triplet:

document.vlinkColor="00FFFF"

参看

document.alinkColor, document.bgColor, document.fgColor, document.linkColor

方法

captureEvents

Sets the document to capture all events of the specified type.

方法源document
实现版本Navigator 4.0

语法

captureEvents(eventType)

参数

eventTypeThe type of event to be captured. The available event types are listed with the event object.

描述

When a window with frames wants to capture events in pages loaded from different locations (servers), you need to use Window.captureEvents in a signed script and precede it with Window.enableExternalCapture. For more information and an example, see Window.enableExternalCapture. captureEvents works in tandem with releaseEvents, routeEvent, and handleEvent. For more information, see "Events in Navigator 4.0".

close

Closes an output stream and forces data sent to layout to display.

方法源document
实现版本Navigator 2.0

语法

close()

参数

无。

描述

The close method closes a stream opened with the document.open method. If the stream was opened to layout, the close method forces the content of the stream to display. Font style tags, such as BIG and CENTER, automatically flush a layout stream.

The close method also stops the "meteor shower" in the Netscape icon and displays Document: Done in the status bar.

示例

The following function calls document.close to close a stream that was opened with document.open. The document.close method forces the content of the stream to display in the window.

function windowWriter1() {
   var myString = "Hello, world!"
   msgWindow.document.open()
   msgWindow.document.write(myString + "<P>")
   msgWindow.document.close()
}

参看

document.open, document.write, document.writeln

getSelection

Returns a string containing the text of the current selection.

方法源document
实现版本Navigator 4.0

语法

getSelection()

描述

This method works only on the current document.

安全性

You cannot determine selected areas in another window.

示例

If you have a form with the following code and you click on the button, JavaScript displays an alert box containing the currently selected text from the window containing the button:

<INPUT TYPE="BUTTON" NAME="getstring"
   VALUE="Show highlighted text (if any)"
   onClick="alert('You have selected:\n'+document.getSelection());">

handleEvent

调用指定事件的控制句柄。

方法源document
实现版本Navigator 4.0

语法

handleEvent(event)

参数

event你想要调用的对象的某一事件控制句柄的名称。

描述

要获得关于事件句柄的更多信息,请看“关于事件的常规信息”

open

Opens a stream to collect the output of write or writeln methods.

方法源document
实现版本Navigator 2.0
Navigator 3.0: 添加了 "replace" parameter; document.open() or document.open("text/html") clears the current document if it has finished loading

语法

open(mimeType, replace)

参数

mimeType(Optional) A string specifying the type of document to which you are writing. If you do not specify mimeType, text/html is the default.
replace(Optional) The string "replace". If you supply this parameter, mimeType must be "text/html". Causes the new document to reuse the history entry that the previous document used.

描述

Sample values for mimeType are:

The open method opens a stream to collect the output of write or writeln methods. If the mimeType is text or image, the stream is opened to layout; otherwise, the stream is opened to a plug-in. If a document exists in the target window, the open method clears it.

End the stream by using the document.close method. The close method causes text or images that were sent to layout to display. After using document.close, call document.open again when you want to begin another output stream.

In Navigator 3.0 and later, document.open or document.open("text/html") clears the current document if it has finished loading. This is because this type of open call writes a default <BASE HREF=> tag so you can generate relative URLs based on the generating script's document base.

The "replace" keyword causes the new document to reuse the history entry that the previous document used. When you specify "replace" while opening a document, the target window's history length is not incremented even after you write and close.

"replace" is typically used on a window that has a blank document or an "about:blank" URL. After "replace" is specified, the write method typically generates HTML for the window, replacing the history entry for the blank URL. Take care when using generated HTML on a window with a blank URL. If you do not specify "replace", the generated HTML has its own history entry, and the user can press the Back button and back up until the frame is empty.

After document.open("text/html","replace") executes, history.current for the target window is the URL of document that executed document.open.

示例

示例 1. The following function calls document.open to open a stream before issuing a write method:

function windowWriter1() {
   var myString = "Hello, world!"
   msgWindow.document.open()
   msgWindow.document.write("<P>" + myString)
   msgWindow.document.close()
}
示例 2. The following function calls document.open with the "replace" keyword to open a stream before issuing write methods. The HTML code in the write methods is written to msgWindow, replacing the current history entry. The history length of msgWindow is not incremented.

function windowWriter2() {
   var myString = "Hello, world!"
   msgWindow.document.open("text/html","replace")
   msgWindow.document.write("<P>" + myString)
   msgWindow.document.write("<P>history.length is " +
      msgWindow.history.length)
   msgWindow.document.close()
}
The following code creates the msgWindow window and calls the function:

msgWindow=window.open('','',
   'toolbar=yes,scrollbars=yes,width=400,height=300')
windowWriter2()
示例 3. In the following example, the probePlugIn function determines whether a user has the Shockwave plug-in installed:

function probePlugIn(mimeType) {
   var havePlugIn = false
   var tiny = window.open("", "teensy", "width=1,height=1")
   if (tiny != null) {
      if (tiny.document.open(mimeType) != null)
         havePlugIn = true
      tiny.close()
   }
   return havePlugIn
}
var haveShockwavePlugIn = probePlugIn("application/x-director")

参看

document.close, document.write, document.writeln, Location.reload, Location.replace

releaseEvents

Sets the document to release captured events of the specified type, sending the event to objects further along the event hierarchy.

方法源document
实现版本Navigator 4.0

Note

If the original target of the event is a window, the window receives the event even if it is set to release that type of event.

语法

releaseEvents(eventType)

参数

eventTypeType of event to be captured.

描述

releaseEvents works in tandem with captureEvents, routeEvent, and handleEvent. For more information, see "Events in Navigator 4.0".

routeEvent

Passes a captured event along the normal event hierarchy.

方法源document
实现版本Navigator 4.0

语法

routeEvent(event)

参数

eventName of the event to be routed.

描述

If a subobject (document or layer) is also capturing the event, the event is sent to that object. Otherwise, it is sent to its original target.

routeEvent works in tandem with captureEvents, releaseEvents, and handleEvent. For more information, see "Events in Navigator 4.0".

write

Writes one or more HTML expressions to a document in the specified window.

方法源document
实现版本Navigator 2.0
Navigator 3.0: users can print and save generated HTML using the commands on the File menu

语法

document.write(expr1, ...,exprN)

参数

expr1, ... exprNAny JavaScript expressions.

描述

The write method displays any number of expressions in the document window. You can specify any JavaScript expression with the write method, including numeric, string, or logical expressions.

The write method is the same as the writeln method, except the write method does not append a newline character to the end of the output.

Use the write method within any SCRIPT tag or within an event handler. Event handlers execute after the original document closes, so the write method implicitly opens a new document of mimeType text/html if you do not explicitly issue a document.open method in the event handler.

You can use the write method to generate HTML and JavaScript code. However, the HTML parser reads the generated code as it is being written, so you might have to escape some characters. For example, the following write method generates a comment and writes it to window2:

window2=window.open('','window2')
beginComment="\<!--"
endComment="--\>"
window2.document.write(beginComment)
window2.document.write(" This some text inside a comment. ")
window2.document.write(endComment)

Printing, saving, and viewing generated HTML

In Navigator 3.0 and later, users can print and save generated HTML using the commands on the File menu.

If you choose Document Source or Frame Source from the View menu, the web browser displays the content of the HTML file with the generated HTML. (This is what would be displayed using a wysiwyg: URL.)

If you instead want to view the HTML source showing the scripts which generate HTML (with the document.write and document.writeln methods), do not use the Document Source or Frame Source menu item. In this situation, use the view-source: protocol.

For example, assume the file file://c|/test.html contains this text:

<HTML>
<BODY>
Hello,
<SCRIPT>document.write(" there.")</SCRIPT>
</BODY>
</HTML>
If you load this URL into the web browser, it displays the following:

Hello, there. If you choose View Document Source, the browser displays:

<HTML>
<BODY>
Hello,
 there.
</BODY>
</HTML>
If you load view-source:file://c|/test.html, the browser displays:

<HTML>
<BODY>
Hello,
<SCRIPT>document.write(" there.")</SCRIPT>
</BODY>
</HTML>
For information on specifying the view-source: protocol in the location object, see the Location object.

示例

In the following example, the write method takes several arguments, including strings, a numeric, and a variable:

var mystery = "world"
// Displays Hello world testing 123
msgWindow.document.write("Hello ", mystery, " testing ", 123)
In the following example, the write method takes two arguments. The first argument is an assignment expression, and the second argument is a string literal.

//Displays Hello world...
msgWindow.document.write(mystr = "Hello ", "world...")
In the following example, the write method takes a single argument that is a conditional expression. If the value of the variable age is less than 18, the method displays "Minor." If the value of age is greater than or equal to 18, the method displays "Adult."

msgWindow.document.write(status = (age >= 18) ? "Adult" : "Minor")

参看

document.close, document.open, document.writeln

writeln

Writes one or more HTML expressions to a document in the specified window and follows them with a newline character.

方法源document
实现版本Navigator 2.0
Navigator 3.0: users can print and save generated HTML using the commands on the File menu

语法

writeln(expr1, ... exprN)

参数

expr1, ... exprNAny JavaScript expressions.

描述

The writeln method displays any number of expressions in a document window. You can specify any JavaScript expression, including numeric, string, or logical expressions.

The writeln method is the same as the write method, except the writeln method appends a newline character to the end of the output. HTML ignores the newline character, except within certain tags such as the PRE tag.

Use the writeln method within any SCRIPT tag or within an event handler. Event handlers execute after the original document closes, so the writeln method will implicitly open a new document of mimeType text/html if you do not explicitly issue a document.open method in the event handler.

示例

All the示例 used for the write method are also valid with the writeln method.

参看

document.close, document.open, document.write


【目录】 【上一页】 【下一页】 【索引】

回页面顶部