JavaScript语言参考手册_目录

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

JavaScript 参考

本书是 JavaScript 语言的参考手册，包括核心语言中的对象和客户端、服务器端的扩展。JavaScript 是 Netscape 跨平台的基于对象的适合于客户和服务器的脚本语言。

本书已经更新于 JavaScript 1.2 的新特性，其它包括了 JavaScript 支持层和样式单的属性和对象。要获得关于这些主题的详细信息，请参看 Netscape Communicator 中的动态 HTML。

目录

此参考中包含的内容
此参考是依照 JavaScript 语言的功能组织的。有时你已经知道了某个对象或方法的名称，但是不太清楚要在哪里能够找到它。这一章包含了解决此种情况的链接表。

轻松上手
本书是 JavaScript 语言的参考手册，包括核心语言中的对象和客户端、服务器端的扩展。JavaScript 是 Netscape 跨平台的基于对象的适用于客户和服务器应用程序的脚本语言。
你应该已经掌握的知识
哪里能找到 JavaScript 的相关信息
文档转换

第一章 简介
这一章简单介绍了 JavaScript，Netscape 跨平台的基于对象的适用于客户和服务器应用程序的脚本语言。
客户端的 JavaScript
服务器端的 JavaScript
JavaScript 对象
JavaScript 安全性

第二章 操作符
JavaScript 有赋值、比较、算术、位、逻辑、字符串和特殊操作符。本章描述了这些操作符，包含了关于操作符优先级的信息。
赋值操作符
比较操作符
算术操作符
% (求余数)
++ (自加)
-- (自减)
- (一元否定)
位操作符
位逻辑运算符
移位操作符
逻辑操作符
简化运算
字符串操作符
特殊操作符
?: (条件操作符)
, (逗号操作符)
delete
new
this
typeof
void

第三章 语句
这一章描述了所有 JavaScript 的语句。JavaScript 语句是用特定的语法由关键词组成的。一个语句可以跨多行。多个语句可以出现在一行上，但各自中间应该用分号隔开。
break
comment
continue
delete
do...while
export
for
for...in
function
if...else
import
labeled
return
switch
var
while
with

第四章 核心
这一章包含了 JavaScript 的核心对象 Array，Boolean，Date，Function，Math，Number，Object 和 String。这些对象同时在客户端和服务器端的 JavaScript 中使用。
Array
属性
方法
Boolean
属性
方法
Date
属性
方法
Function
属性
方法
Math
属性
方法
Number
属性
方法
Object
属性
方法
String
属性
方法
RegExp
属性
方法

第五章 文档
这一章对应于文档及其关联对象 document，Layer，Link，Anchor，Area，Image 和 Applet。
document
属性
方法
Link
属性
方法
Area
Anchor
Image
属性
方法
Applet
Layer
属性
方法

第六章 窗口
这一章对应于 Window 对象和客户端与之相关的对象：Frame，Location 和 History。
Window
属性
方法
Frame
Location
属性
方法
History
属性
方法
screen
属性

第七章 表单
这一章对应于使用表单，表单是出现在文档中用于从用户获得输入的。
Form
属性
方法
Hidden
属性
Text
属性
方法
Textarea
属性
方法
Password
属性
方法
FileUpload
属性
方法
Button
属性
方法
Submit
属性
方法
Reset
属性
方法
Radio
属性
方法
Checkbox
属性
方法
Select
属性
方法
Option
属性

第八章 浏览器

这一章对应了浏览器及其关联的元素。
navigator
属性
方法
MimeType
属性
Plugin
属性

第九章 事件和事件句柄

这一章包含了在 JavaScript客户端用于激发某些特定动作的事件对象和事件句柄。另外，本章还包括了关于使用事件和事件句柄的常规信息。
关于事件常规信息
定义事件句柄
Navigator 4.0 中的事件
event
onAbort
onBlur
onChange
onClick
onDblClick
onDragDrop
onError
onFocus
onKeyDown
onKeyPress
onKeyUp
onLoad
onMouseDown
onMouseMove
onMouseOut
onMouseOver
onMouseUp
onMove
onReset
onResize
onSelect
onSubmit
onUnload

第十章 LiveWire 数据库服务

本章包含了服务器端与 LiveWire 关联的对象：database，DbPool，Connection，Cursor，Stproc，Resultset 和 blob。
database
事务
属性
方法
DbPool
属性
方法
Connection
属性
方法
Cursor
属性
方法
Stproc
属性
方法
Resultset
属性
方法
blob
方法

第十一章 进程管理服务

本章包含了与管理进程相关的服务器端对象，其中有 request，client，project，server 和 Lock。
request
属性
client
属性
方法
project
属性
方法
server
属性
方法
Lock
方法

第十二章实用工具

本章包含了服务器端的对象 File 和 SendMail。
File
属性
方法
SendMail
属性
方法

第十三章 全程函数

本章包含了所有 JavaScript 中未与任何对象关联的函数。
addClient
addResponseHeader
blob
callC
debug
deleteResponseHeader
escape
eval
flush
getOptionValue
getOptionValueCount
isNaN
Number
parseFloat
parseInt
redirect
registerCFunction
ssjs_generateClientID
ssjs_getCGIVariable
ssjs_getClientID
String
taint
unescape
untaint
write

第十四章 LiveConnect 的 Java 包
netscape.javascript.JSObject
方法和静态方法
netscape.javascript.JSException
构造函数
netscape.plugin.Plugin
构造函数和方法

索引

【下一章】 【索引】 【这是目录】

回页面顶部 回页面顶部


JavaScript语言参考手册_浏览器

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

第八章
浏览器

本章对应于浏览器及其相关元素。

表 8.1 本章中对象概览

表 8.1 浏览器相关对象
对象 | 描述
navigator | 包含了关于正在使用的 Navigator 的版本。
MimeType | 描述了客户端支持的 MIME 类型(多部分网际邮件扩展)。
Plugin | 描述了客户端安装的插件模块。

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


JavaScript语言参考手册_浏览器

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

navigator

包含了正在使用的 Navigator 的版本信息。

客户端对象 |
实现版本 | Navigator 2.0 Navigator 3.0: 添加了 mimeTypes 和 plugins 属性；添加了 javaEnabled 和 taintEnabled 方法。 Navigator 4.0: 添加了 language 和 platform 属性；添加了 preference 方法。

创建源

JavaScript 客户端运行时刻引擎自动创建 navigator 对象。

描述

使用 navigator 对象可以决定你的用户正在使用的 Navigator 的版本，用户的 Navigator 可以控制的 MIME 类型，用户已经安装的插件。所有这些 navigator 的属性都是只读的。

属性概览

appCodeName | 指定浏览器的代码名称。
appName | 指定浏览器的名称。
appVersion | 指定 Navigator 的版本信息。
language | 标明正在使用的 Navigator 的翻译语种。
mimeTypes | 客户端支持的所有 MIME 类型数组。
platform | 标明了 Navigator 编译适合的机器类型。
plugins | 客户端已安装的所有插件数组。
userAgent | 指定了用户代理头。

方法概览

javaEnabled | 测试是否允许 Java。
plugins.refresh | 使新安装的插件有效，并可选重新装入已打开的包含插件的文档。
preference | 允许一个已标识的脚本获取并设置特定的 Navigator 参数。
taintEnabled | 指定是否允许数据污点。

属性

appCodeName

 指定了浏览器代码名称的字符串。

属性源 | navigator
只读 |
实现版本 | Navigator 2.0

示例

下面的例子显示了 appCodeName 属性的值：

document.write("navigator.appCodeName 的值是 " +
navigator.appCodeName)
对于 Navigator 2.0 和 3.0，此语句将显示下列文字：

navigator.appCodeName 的值是 Mozilla

appName

指定了浏览器名称的字符串。

属性源 | navigator
只读 |
实现版本 | Navigator 2.0

示例

下面的例子显示了 appName 属性的值：

document.write("navigator.appName 的值是 " +
navigator.appName)
 对于 Navigator 2.0 和 3.0，此语句将显示下列文字：

navigator.appName 的值是 Netscape

appVersion

指定了 Navigator 版本信息的字符串。

属性源 | navigator
只读 |
实现版本 | Navigator 2.0

描述

appVersion 属性将以下列格式指定版本信息：

releaseNumber (platform; country)

此格式中包含下列值：

  • releaseNumber 是 Navigator 的版本号。例如，“2.0b4
    • ”指定了 Navigator 2.0, beta 4。

  • platform 是 Navigator 运行的平台。例如，“Win16”指定了 16 位版本的 Windows，如 Windows 3.1。

  • country 对于国际版本来说是“I”，对于美国本土版本来说是“U”。本土版本相对于国际版本来说，有更强的加密特性。
    •

示例

 示例 1. 下面的例子将显示 Navigator 的版本信息：

document.write("navigator.appVersion 的值是 " +
navigator.appVersion)
 对于在 Windows 95 上运行的 Navigator 2.0，将显示下列信息：
navigator.appVersion 的值是 2.0 (Win95, I)

对于在 Windows NT 上运行的 Navigator 3.0，将显示下列信息：
navigator.appVersion 的值是 3.0 (WinNT, I)

示例 2. 下面的例子将用换行符分隔每一行字符来填充 Textarea 对象。因为换行字符会根据不同的平台而有不同，示例将测试 appVersion 属性决定用户是否正在运行 Windows (appVersion 对于所有版本的 Windows 来说都包含“Win”)。如果用户正在运行 Windows，换行符将设定为 \r\n；否则将设定为 \n，这是针对 Unix 和 Macintosh 来说的。

<SCRIPT>
var newline=null
function populate(textareaObject){
if (navigator.appVersion.lastIndexOf('Win') != -1)
newline="\r\n"
else newline="\n"
textareaObject.value="第一行" + newline + "第二行" + newline
+ "line 3"
}
</SCRIPT>
<FORM NAME="form1">
<BR><TEXTAREA NAME="testLines" ROWS=8 COLS=55></TEXTAREA>
<P><INPUT TYPE="button" VALUE="填充 Textarea 对象"
onClick="populate(document.form1.testLines)">
</TEXTAREA>
</FORM>

language

标明了正在使用的 Navigator 的翻译版本。

属性源 | navigator
只读 |
实现版本 | Navigator 4.0

描述

language 的值通常是两个字母的代码，如“en”；某些情况下也可能是五个字符的代码以标明语言子类型，如“zh_CN”。

使用该属性可以决定客户使用的 Navigator 的语言版本，你可能想要为不同语言的用户显示不同的翻译文本。

mimeTypes

一个包含有客户端所有支持的 MIME 类型的数组。

属性源 | navigator
只读 |
实现版本 | Navigator 3.0

mimeTypes 数组包含了客户端支持的每一个 MIME 类型(实际上，这是由帮助应用程序或插件实现的)。例如，如果一个客户端支持三种 MIME 类型，这些 MIME 类型将被反映到 navigator.mimeTypes[0]、navigator.mimeTypes[1]，和 navigator.mimeTypes[2] 中。

mimeTypes 数组的每一个元素都是一个 MimeType 对象。

参看

MimeType

platform

标明了 Navigator 编译的机器类型。

属性源 | navigator
只读 |
实现版本 | Navigator 4.0

描述

Platform 值可能是 Win32、Win16、Mac68k、MacPPC 和各种 Unix。

由于版本差异、模拟器或其它原因，Navigator 根据不同的机器类型编译的版本会有一定的出入。

如果你使用 SmartUpdate 向用户机器上下载软件，就可以使用此特性保证触发器下载的是对应的 JAR 文件。触发页将在检查 platform 属性前检查 Navigator 的版本。要获得关于使用 SmartUpdate 更多的信息，请参看将 JAR 安装管理器用于 SmartUpdate。

plugins

包含了客户端目前安装的所有插件的数组。

属性源 | navigator
只读 |
实现版本 | Navigator 3.0

使用本数组可以引用客户端安装的 Plugin 对象。plugins 数组的每个元素都是一个 Plugin 对象。例如，如果在客户端安装了三个插件，这三个插件将被映射为 navigator.plugins[0]、navigator.plugins[1] 和 navigator.plugins[2].

要使用 plugins 数组：

1. navigator.plugins[index]
2. navigator.plugins[index][mimeTypeIndex]
index 是一个表明客户端所安装插件顺序的整型数，或者是包含 Plugin 对象名称(可从 name 属性中查到)的字符串。第一种格式将返回存储在 plugins 数组中指定位置的 Plugin 对象。第二种格式将返回该 Plugin 对象中的 MimeType 对象。

要获得客户端已安装的插件数目，可以使用 length 属性：navigator.plugins.length。

plugins.refresh: plugins 数组有其自己的方法，refresh。此方法将使得最新安装的插件可用，更新相关数组，如 plugins 数组，并可选重新装入包含插件的已打开文档。你可以使用下列语句调用该方法：

navigator.plugins.refresh(true)
navigator.plugins.refresh(false)
如果你给定 true 的话，refresh 将在使得新安装的插件可用的同时，重新装入所有包含有嵌入对象(EMBED 标签)的文档。如果你给定 false 的话，该方法则只会刷新 plugins 数组，而不会重新载入任何文档。

当用户安装插件后，该插件将不会可用，除非调用了 refresh，或者用户关闭并重新启动了 Navigator。

示例

下面的代码将刷新数组并重新装入包含有嵌入对象的文档：

navigator.plugins.refresh(true)
同时可参看 Plugin 对象的示例。

userAgent

该字符串表明从客户端向服务器发送的 HTTP 协议用户代理头的值。

属性源 | navigator
只读 |
实现版本 | Navigator 2.0

描述

服务器使用在用户代理头中发送的值来鉴别客户。

示例

下面的例子将显示 Navigator 中的 userAgent 信息：

document.write("navigator.userAgent 的值是 " +
navigator.userAgent)
对于 Navigator 2.0，将显示下列内容：

navigator.userAgent 的值是 Mozilla/2.0 (Win16; I)

方法

javaEnabled

 测试是否允许 Java。

方法源 | navigator
静态 |
实现版本 | Navigator 3.0

语法

javaEnabled()

参数

 无。

描述

如果允许 Java 的话，javaEnabled 将返回 true；否则将返回 false。用户可以通过用户首选项的参数设置启用或禁用 Java。

示例

下面的代码将在允许 Java 的情况下执行 function1；否则执行 function2。

if (navigator.javaEnabled()) {
function1()
}
else function2()

参看

navigator.appCodeName, navigator.appName, navigator.userAgent

preference

允许标识的脚本获取并设置某些 Navigator 的首选项。

方法源 | navigator
静态 |
实现版本 | Navigator 4.0

语法

preference(prefName)
preference(prefName, setValue)

参数

prefName | 表明了你想要获取或设置的首选项的名称。可以选用下面列出的首选项。
setValue | 你想要为首选项指定的值。可以是字符串、数值或布尔值。

描述

本方法将返回首选项的值。如果你使用本方法设置值，则将返回新值。

安全性

使用 preference 方法读取首选项需要有 UniversalPreferencesRead 权限。用此方法设置首选项需要有 UniversalPreferencesWrite 权限。

要获得关于 Navigator 4.0 中的安全性的更详细信息，请看“JavaScript 指南”中的第七章“JavaScript 安全性”。

在得到许可的情况下，你可以获取和设置在表 8.2 中列出的首选项。

表 8.2 参数选择
要做下列事... | 设置此参数... | 为...
允许或禁止自动装入图像 | general.always_load_images | true 或 false
允许或禁止 Java | security.enable_java | true 或 false
允许或禁止 JavaScript | javascript.enabled | true 或 false
允许或禁止样式表 | browser.enable_style_sheets | true 或 false
允许或禁止 SmartUpdate | autoupdate.enabled | true 或 false
接受所有 cookie | network.cookie.cookieBehavior | 0
只接受发送回原始服务器的 cookie | network.cookie.cookieBehavior | 1
禁止 cookie | network.cookie.cookieBehavior | 2
接受 cookie 前警告 | network.cookie.warnAboutCookies | true 或 false

taintEnabled

指定是否允许数据污点。

方法源 | navigator
静态 |
实现版本 | Navigator 3.0; 在 Navigator 4.0 中已删除

语法

navigator.taintEnabled()

描述

 污点将避免其它脚本传递绝密和私有的信息，例如目录结构或用户浏览历史。JavaScript 不能在没有最终用户许可的情况下向任何服务器发送带有污点的值。

可以使用 taintEnabled 决定是否允许数据污点。如果允许数据污点的话，taintEnabled 将返回 true，否则返回 false。用户可以环境变量 NS_ENABLE_TAINT 启用或禁用数据污点。

示例

下面的代码将在允许数据污点的情况下执行 function1；否则执行 function2。

if (navigator.taintEnabled()) {
function1()
}
else function2()

参看

taint, untaint

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


JavaScript语言参考手册_浏览器

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

MimeType

 客户端支持的一个 MIME(多部分网际邮件扩展，Multipart Internet Mail Extension) 类型。

客户端对象 |
实现版本 | Navigator 3.0

创建源

你不需要自行创建 MimeType 对象。这些对象是预先定义的 JavaScript 对象，你可以通过 navigator 或 Plugin 对象的 mimeTypes 数组来访问这些对象：

navigator.mimeTypes[index]
这里 index 或者是表明由客户端支持的 MIME 类型的整型值，也可以是包含了 MimeType 对象类型(来自于 MimeType.type 属性)的字符串。

描述

每个 MimeType 对象都是 mimeTypes 数组中的一个元素。mimeTypes 数组是 navigator 和 Plugin 对象的一个属性。例如，下表将显示 JPEG 图像的值给出了一个总结：

表达式 | 值
navigator.mimeTypes["image/jpeg"].type | image/jpeg
navigator.mimeTypes["image/jpeg"].description | JPEG Image
navigator.mimeTypes["image/jpeg"].suffixes | jpeg, jpg, jpe, jfif, pjpeg, pjp
navigator.mimeTypes["image/jpeg"].enabledPlugins | null

属性概览

description | MIME 类型的描述。
enabledPlugin | 对为该 MIME 类型配置好的 Plugin 对象的引用。
suffixes | 列出了该 MIME 类型可能对应文件扩展名的字符串，如“mpeg, mpg, mpe, mpv, vbs, mpegv”。
type | 该 MIME 类型的名称，如“video/mpeg”或“audio/x-wav”。

方法

无。

示例

下面的代码将显示客户端上每个 MimeType 对象的 type、description、suffixes 和 enabledPlugin 属性：

document.writeln("<TABLE BORDER=1><TR VALIGN=TOP>",
"<TH ALIGN=left>i",
"<TH ALIGN=left>type",
"<TH ALIGN=left>description",
"<TH ALIGN=left>suffixes",
"<TH ALIGN=left>enabledPlugin.name</TR>")
for (i=0; i < navigator.mimeTypes.length; i++) {
document.writeln("<TR VALIGN=TOP><TD>",i,
"<TD>",navigator.mimeTypes[i].type,
"<TD>",navigator.mimeTypes[i].description,
"<TD>",navigator.mimeTypes[i].suffixes)
if (navigator.mimeTypes[i].enabledPlugin==null) {
document.writeln(
"<TD>无",
"</TR>")
} else {
document.writeln(
"<TD>",navigator.mimeTypes[i].enabledPlugin.name,
"</TR>")
}
}
document.writeln("</TABLE>")

上面的例子输出结果与下表相似：

i | type | description | suffixes | enabledPlugin.name
0 | audio/aiff | AIFF | aif, aiff | LiveAudio
1 | audio/wav | WAV | wav | LiveAudio
2 | audio/x-midi | MIDI | mid, midi | LiveAudio
3 | audio/midi | MIDI | mid, midi | LiveAudio
4 | video/msvideo | Video for Windows | avi | NPAVI32 Dynamic Link Library
5 | * | Netscape Default Plugin |  | Netscape Default Plugin
6 | zz-application/zz-winassoc-TGZ |  | TGZ | 无

参看

navigator, navigator.mimeTypes, Plugin

属性

description

 用可读语言来描述的该 MIME 类型对象的数据类型。

属性源 | MimeType
只读 |
实现版本 | Navigator 3.0

enabledPlugin

为特定的 MIME 类型配置好的 Plugin 对象。如果该 MIME 类型没有配置插件，则 enabledPlugin 为空。

属性源 | MimeType
只读 |
实现版本 | Navigator 3.0

描述

使用 enabledPlugin 属性决定哪个插件是为特定的 MIME 类型配置的。每个插件可能支持多个 MIME 类型，并且每个 MIME 类型也可被多个插件支持。不过，一个 MIME 类型只能被配置一个插件。(在 Macintosh 和 Unix 上，用户可以为每个 MIME 类型配置控制程序；在 Windows 上，控制程序是在浏览器启动时确定的。)

enabledPlugin 属性是对该指定 MIME 类型配置的插件的 Plugin 对象的引用。

你也许需要知道对于一个 MIME 类型配置的是哪个插件。例如，在用户有支持某 MIME 类型的插件时动态生成一个 EMBED 标签。

示例

下面的例子将确定是否安装了 Shockwave 插件。如果已经安装了的话，将显示一部影片。

// 先检查是否可以显示 Shockwave 影片。
mimetype = navigator.mimeTypes["application/x-director"]
if (mimetype) {
// 如果是的话，现在再看看能不能用插件显示影片。
plugin = mimetype.enabledPlugin
if (plugin)
// 如果是的话，就将影片嵌入到当前文档。
document.writeln("看看这部影片：<EMBED SRC=mymovie.dir HEIGHT=100 WIDTH=100>")
else
// 否则的话，就提供一个到影片的链接。
document.writeln("<A HREF='mymovie.dir'>按此</A>观看影片。")
} else {
// 否则的话，就显示。。。
document.writeln("真遗憾，您享受不了这部超级酷的影片。")
}

suffixes

用字符串的形式列出了该 MIME 类型所有可能的文件后缀(即扩展名)。

属性源 | MimeType
只读 |
实现版本 | Navigator 3.0

描述

suffixes 属性是一个包含每个合法后缀(通常为三个字符)的字符串，中间用逗号分隔。例如，“audio/x-midi”MIME 类型的 suffixes 属性为“mid, midi”。

type

指定了 MIME 类型名称的字符串。该字符串将用于区别 MIME 类型；如“video/mpeg”或“audio/x-wav”。

属性源 | MimeType
只读 |
实现版本 | Navigator 3.0

属性源

MimeType

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

回页面顶部 回页面顶部


JavaScript语言参考手册_浏览器

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

Plugin

 在客户端上安装的一个插件模块。

客户端对象 |
实现版本 | Navigator 3.0

创建源

Plugin 对象是 JavaScript 的预定义对象，你可以通过 navigator.plugins 数组访问它们。

描述

一个 Plugin 对象就是一个安装在客户端的插件。所谓插件，就是浏览器用于显示特定类型嵌入数据时调用的软件模块。用户从帮助菜单中选择关于插件选项可以获取已安装插件的清单。

每个 Plugin 对象本身都是一个数组，其中包含的每个元素分别对应于每个该插件支持的 MIME 类型。而数组的每个元素都是一个 MimeType 对象。例如，下面的代码将显示第一个 Plugin 对象的第一个 MimeType 对象的 type 和描述 属性。

myPlugin=navigator.plugins[0]
myMimeType=myPlugin[0]
document.writeln('myMimeType.type 为 ',myMimeType.type,"<BR>")
document.writeln('myMimeType.description 为 ',myMimeType.description)

而此代码的显示输出与下列内容相似：

myMimeType.type 为 video/quicktime
myMimeType.description 为 QuickTime for Windows

Plugin 对象使你可以动态判断客户端上安装了哪些插件。你可以编写这样的脚本，用于在已安装对应的插件时显示嵌入插件数据，而在没有安装对应插件的时候显示某些如图像或文本等的替换信息。

插件可能是与平台相关的或可配置的，所以 Plugin 对象的 MimeType 对象数组在不同的平台或用户那里的情况可能并不相同。

每个 Plugin 对象都是 plugins 数组中的一个元素。

当你使用 EMBED 标记从插件应用程序中生成输出的时候，你就不能创建 Plugin 对象。你可以使用 document.embeds 数组获取对用 EMBED 标记创建的插件实例的引用。详细内容请参看 document.embeds 数组。

属性概览

description | 插件的描述。
filename | 插件文件在磁盘上的文件名。
length | 插件中 MimeType 对象数组的元素个数。
name | 插件的名称。

示例

示例 1 用户可以从帮助菜单中选择关于插件获取已安装的插件列表。要查看浏览器完成此报表的源代码，可以首先从帮助菜单中选择关于插件选项，然后从查看菜单中选择页面源文件。

示例 2 下列代码将把预定义的 LiveAudio 属性赋给简明变量。

var myPluginName = navigator.plugins["LiveAudio"].name
var myPluginFile = navigator.plugins["LiveAudio"].filename
var myPluginDesc = navigator.plugins["LiveAudio"].description

示例 3 下面的代码将在已安装 LiveAudio 的情况下显示消息“LiveAudio 已经配置为 audio/wav”，也就是说它对应于“audio/wav”MIME类型：

var myPlugin = navigator.plugins["LiveAudio"]
var myType = myPlugin["audio/wav"]
if (myType && myType.enabledPlugin == myPlugin)
document.writeln("LiveAudio 已经配置为 audio/wav")

示例 4 下面的表达式将呈现出 Shockwave 可以显示的 MIME 类型数目：

navigator.plugins["Shockwave"].length

示例 5 下面的代码将列出一张表，其中显示了客户端每个 Plugin 对象的 name、filename、description 和 length 属性：

document.writeln("<TABLE BORDER=1><TR VALIGN=TOP>",
"<TH ALIGN=left>i",
"<TH ALIGN=left>名称",
"<TH ALIGN=left>文件名",
"<TH ALIGN=left>描述",
"<TH ALIGN=left>类型数</TR>")
for (i=0; i < navigator.plugins.length; i++) {
document.writeln("<TR VALIGN=TOP><TD>",i,
"<TD>",navigator.plugins[i].name,
"<TD>",navigator.plugins[i].filename,
"<TD>",navigator.plugins[i].description,
"<TD>",navigator.plugins[i].length,
"</TR>")
}
document.writeln("</TABLE>") 上面例子的输出结果与下面类似：

i | 名称 | 文件名 | 描述 | 类型数
0 | QuickTime Plug-In | d:\nettools\netscape\nav30\Program\ plugins\NPQTW32.DLL | QuickTime Plug-In for Win32 v.1.0.0 | 1
1 | LiveAudio | d:\nettools\netscape\nav30\Program\ plugins\NPAUDIO.DLL | LiveAudio - Netscape Navigator sound playing component | 7
2 | NPAVI32 Dynamic Link Library | d:\nettools\netscape\nav30\Program\ plugins\npavi32.dll | NPAVI32, avi plugin DLL | 2
3 | Netscape Default Plugin | d:\nettools\netscape\nav30\Program\ plugins\npnul32.dll | Null Plugin | 1

参看

MimeType, document.embeds

属性

description

 人工可阅读的插件描述。该文本由插件开发者提供。

属性源 | Plugin
只读 |
实现版本 | Navigator 3.0

filename

插件文件在磁盘上的名称。

属性源 | Plugin
只读 |
实现版本 | Navigator 3.0

描述

filename 属性是插件程序文件名，由插件自身提供。该名称可能因平台不同而不同。

示例

参看 Plugin 的示例。

length

MimeType 对象的插件数组中的元素个数。

属性源 | Plugin
只读 |
实现版本 | Navigator 3.0

name

指定插件名称的字符串。

属性源 | Plugin
只读 |
实现版本 | Navigator 3.0

安全性

Navigator 3.0: 该属性缺省情况下是带有污点的。要获得关于数据污点更多的信息，请看“JavaScript 安全性”。

描述

插件的名称，由插件自身提供。每个插件都应该有一个唯一的名称标识自身。

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


JavaScript语言参考手册_表单

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

Button

 HTML 表单上的一个按钮。

客户端对象 |
实现版本 | Navigator 2.0 Navigator 3.0: 添加了 type 属性; 添加了 onBlur 和 onFocus 事件句柄；添加了 blur 和 focus 方法。 Navigator 4.0: 添加了 handleEvent 方法。

创建源

TYPE 属性为“button”的 HTML INPUT 标签可创建此种对象。对于一个给定的表单，JavaScript 运行时刻引擎将为每个按钮创建一个独立的 Button 对象，然后将它们放在对应的 Form 对象的 elements 数组中。通过对该数组的索引，你可访问一个 Button 对象。具体方法是使用编号或者在已知 NAME 属性的情况下使用之。

事件句柄

  • onBlur
  • onClick
  • onFocus
  • onMouseDown
  • onMouseUp

描述

 表单上的 Button 对象看起来与下图类似：

一个 Button 对象就是一个表单元素，必须在 FORM 标签中定义。

Button 对象是一种自定义的按钮，你可以用来执行任何你定义的操作。该按钮将执行其 onClick 事件控制句柄中的脚本。

属性概览

form | 指定了包含该 Button 对象的表单。
name | 对应于 NAME 属性。
type | 对应于 TYPE 属性。
value | 对应于 VALUE 属性。

方法概览

blur | 从按钮上移除焦点。
click | 模拟对按钮的单击。
focus | 将焦点移至按钮。
handleEvent | 调用指定事件的控制句柄。

示例

 下面的例子创建了一个叫做“calcButton”的按钮，其上显示了文本“计算”。当单击该按钮时，将调用 calcFunction 函数。

<INPUT TYPE="button" VALUE="Calculate" NAME="calcButton"
onClick="calcFunction(this.form)">

参看

Form, Reset, Submit

属性

form

 对包含该按钮的窗体的引用。

属性源 | Button
只读 |
实现版本 | Navigator 2.0

描述

每个表单元素都有一个 form 属性用于指向元素的父表单。该属性在事件控制句柄中特别有用，你可能想要由其获得当前表单中其它元素。每个表单元素都有一个 form 属性用于指向元素的父表单。该属性在事件控制句柄中特别有用，你可能想要由其获得当前表单中其它元素。

示例

示例 1. 在下面的例子中，窗体 myForm 包含了一个 Text 对象和一个按钮。当用户单击按钮的时候，窗体的名字就将赋给 Text 对象。按钮的 onClick 事件控制句柄使用 this.form 来引用父窗体 myForm。

<FORM NAME="myForm">
窗体名称：<INPUT TYPE="text" NAME="text1" VALUE="爱啥是啥">
<P>
<INPUT NAME="button1" TYPE="button" VALUE="显示窗体名称"
onClick="this.form.text1.value=this.form.name">
</FORM>

示例 2. 下面的例子显示了带有几个元素的窗体。当用户单击 button2 时，函数 showElements 将显示一个警告对话框，里面包含了窗体 myForm 上的每个元素的名称。

function showElements(theForm) {
str = "窗体 " + theForm.name + " 的元素包括：\n "
for (i = 0; i < theForm.length; i++)
str += theForm.elements[i].name + "\n"
alert(str)
}
</script>
<FORM NAME="myForm">
窗体名称：<INPUT TYPE="text" NAME="text1" VALUE="爱啥是啥">
<P>
<INPUT NAME="button1" TYPE="button" VALUE="显示窗体名称"
onClick="this.form.text1.value=this.form.name">
<INPUT NAME="button2" TYPE="button" VALUE="显示窗体元素"
onClick="showElements(this.form)">
</FORM>

警告对话框将显示下列文本：

JavaScript 警告：
窗体 myForm 的元素包括：
text1
button1
button2

示例 3. 下面的例子使用对象引用，而不是关键字来参考窗体。下面的代码将返回对 myForm 的引用，其中包含了 myButton。

document.myForm.myButton.form

参看

Form

name

指定了按钮名称的字符串。

属性源 | Button
实现版本 | Navigator 2.0

安全性

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

描述

name 属性实际上对应于 NAME 属性。更改 name 属性将覆盖此规定。

不要混淆 name 属性和在按钮上显示的文本。value 属性对应于按钮上显示的文本。name 属性不会显示在屏幕上；它是用来在编程上引用对象的。

如果同一表单中有多个 NAME 属性相同的对象，将会自动创建一个该名称的数组。该数组中的每一个元素描述一个单独的对象。元素按照源文件的顺序从 0 开始依次索引。例如，如果相同窗体中有 NAME 属性同为“myField”的两个 Text 元素和一个 Button 元素，将会自动创建元素为 myField[0]、myField[1] 和 myField[2] 的数组。你需要在代码中注意到这种情况，并且自行识别 myField 到底是对单个元素还是元素的数组的引用。

示例

在下面的例子中，valueGetter 函数将使用循环来遍历 valueTest 窗体中的元素数组。msgWindow 窗口将显示该窗体中所有元素的名称：

newWindow=window.open("http://home.netscape.com")
function valueGetter() {
var msgWindow=window.open("")
for (var i = 0; i < newWindow.document.valueTest.elements.length; i++) {
msgWindow.document.write(newWindow.document.valueTest.elements[i].name + "<BR>")
}
}

在下面的例子中，第一条语句创建一个叫做 netscapeWin 的窗口。第二条语句在警告对话框中显示值“netscapeHomePage”，因为“netscapeHomePage”是 netscapeWin 的 windowName 参数的值。

netscapeWin=window.open("http://home.netscape.com","netscapeHomePage")
alert(netscapeWin.name)

参看

Button.value

type

对于所有的 Button 对象，type 属性的值都是“button”。该属性指定了表单元素的类型。

属性源 | Button
只读 |
实现版本 | Navigator 3.0

示例

下面的例子将把表单中的每个元素的 type 属性写到文档中。

for (var i = 0; i < document.form1.elements.length; i++) {
document.writeln("<BR>type is " + document.form1.elements[i].type)
}

value

对应于按钮的 VALUE 属性的字符串。

属性源 | Button
只读 | Mac and UNIX
实现版本 | Navigator 2.0

安全性

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

描述

该字符串显示于按钮的表面上。

在 Macintosh 和 UNIX 系统中概属性是只读的。在 Windows 上，你可以更改此属性。

如果在 HTML 中没有指定 VALUE 属性，value 属性将为空字符串。

不要混淆 value 属性和 name 属性。name 属性不会显示在屏幕上；它是用来在编程上引用对象的。

示例

下面的函数将获取每组按钮的 value 属性，并将其显示在 msgWindow 窗口中：

function valueGetter() {
var msgWindow=window.open("")
msgWindow.document.write("submitButton.value 为 " +
document.valueTest.submitButton.value + "<BR>")
msgWindow.document.write("resetButton.value 为 " +
document.valueTest.resetButton.value + "<BR>")
msgWindow.document.write("helpButton.value 为 " +
document.valueTest.helpButton.value + "<BR>")
msgWindow.document.close()
}

该例子将显示下列值：

Query Submit
Reset
帮助

上面的例子假定按钮定义如下：

<INPUT TYPE="submit" NAME="submitButton">
<INPUT TYPE="reset" NAME="resetButton">
<INPUT TYPE="button" NAME="helpButton" VALUE="帮助">

参看

Button.name

方法

blur

 从按钮中移除焦点。

方法源 | Button
实现版本 | Navigator 2.0

语法

blur()

参数

 无

示例

下面的例子将把焦点从元素 userButton 中移除：

userButton.blur()

这个例子假定按钮定义如下：

<INPUT TYPE="button" NAME="userButton">

参看

Button.focus

click

模拟鼠标单击按钮，但是并不触发按钮的 onClick 事件控制句柄。

方法源 | Button
实现版本 | Navigator 2.0

语法

click()

参数

 无。

安全性

Navigator 4.0：将表单提交给 mailto: 或 news: URL 需要有 UniversalSendMail 权限。要获取 Navigator 4.0 中关于安全性更多的信息，请看“JavaScript 指南”中的第七章“JavaScript 安全性”。

focus

将焦点移至该按钮处。

方法源 | Button
实现版本 | Navigator 2.0

语法

focus()

参数

 无。

参看

Button.blur

handleEvent

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

方法源 | Button
实现版本 | Navigator 4.0

语法

handleEvent(event)

参数

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

描述

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


JavaScript语言参考手册_表单

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

Submit

 一个 HTML 表单上的提交按钮。提交按钮将导致表单被提交。

客户端对象 |
实现版本 | Navigator 2.0 Navigator 3.0: 添加了 type 属性; 添加了 onBlur 和 onFocus 事件控制句柄；添加了 blur 和 focus 方法。 Navigator 4.0: 添加了 handleEvent 方法。

创建源

带有“submit”作为 TYPE 属性的 HTML INPUT 标记。对于一个给定的表单，JavaScript 运行时刻引擎将创建一个对应的 Submit 对象并将其放置在对应的 Form 对象的 elements 数组中。你可以通过该数组的索引访问 Submit 对象。你可以使用数值或在提供了 NAME 属性的情况下使用 NAME 索引该数组。

事件句柄

  • onBlur
  • onClick
  • onFocus

安全性

 Navigator 4.0：将表单提交到 mailto: 或 news: URL 需要有 UniversalSendMail 权限。要获取 Navigator 4.0 中关于安全性更多的信息，请看“JavaScript 指南”中的第七章“JavaScript 安全性”。

描述

表单中的一个 Submit 对象看起来像这样：

Submit 对象是一个表单元素，必须在 FORM 标记内定义。

单击提交按钮将把表单提交到由表单的 action 属性指定的 URL。此行为通常是在客户端装入一个新页面；也可能与当前页相同，如果 action 属性确实是这么指定的或者根本就没有指定 action 属性。

提交按钮的 onClick 事件句柄不能阻止表单被提交；相反，你应该使用表单的 onSubmit 事件句柄或者使用 submit 方法而不是 Submit 对象。请参看 Form 对象的示例。

属性概览

form | 指定了包含 Submit 对象的表单。
name | 反映了 NAME 属性。
type | 反映了 TYPE 属性。
value | 反映了 VALUE 属性。

方法概览

blur | 将焦点从提交按钮移开。
click | 模拟对提交按钮的单击。
focus | 将焦点移至提交按钮。
handleEvent | 调用指定事件的控制句柄。

示例

下面的例子将创建一个叫做 submitButton 的 Submit 对象。文本“完成”显示在按钮的表面上。

<INPUT TYPE="submit" NAME="submitButton" VALUE="完成">

请参看 Form 的示例。

参看

Button, Form, Reset, Form.submit, onSubmit

属性

form

 对包含该提交按钮的表单的引用。

属性源 | Submit
只读 |
实现版本 | Navigator 2.0

描述

每个表单元素都有一个 form 属性用于指向元素的父表单。该属性在事件控制句柄中特别有用，你可能想要由其获得当前表单中其它元素。

示例

下面的例子演示了带有几个元素的表单。当用户单击 button2 时，函数 showElements 将显示一个警告框，其中包含了表单 myForm 中每个元素的名称。

<SCRIPT>
function showElements(theForm) {
str = "表单 " + theForm.name + " 的表单元素有：\n "
for (i = 0; i < theForm.length; i++)
str += theForm.elements[i].name + "\n"
alert(str)
}
</SCRIPT>
<FORM NAME="myForm">
表单名称：<INPUT TYPE="text" NAME="text1" VALUE="Beluga">
<P>
<INPUT NAME="button1" TYPE="button" VALUE="显示表单名称"
onClick="this.form.text1.value=this.form.name">
<INPUT NAME="button2" TYPE="submit" VALUE="显示表单元素"
onClick="showElements(this.form)">
</FORM>
警告框中将显示下列文本：

表单 myForm 的表单元素有：
text1
button1
button2

参看

Form

name

指定了提交按钮名称的字符串。

属性源 | Submit
实现版本 | Navigator 2.0

安全性

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

描述

name 属性实际上反映的是 NAME 属性的值。更改 name 属性将覆盖此设置。

不要混淆 name 属性和显示在按钮表面上的文本。value 属性指定了该按钮的表面文本。name 属性并不显示在屏幕上；它仅仅用于编程时对该按钮的引用。

如果在同一个表单上出现了多个有相同 NAME 属性的对象，将会自动创建一个给定名称的数组。该数组中的每个元素都代表着一个独立的 Form 对象。元素将根据源文件中的顺序从 0 开始编号。例如，如果在同一表单上有两个 Text 元素和一个 Submit 元素的 NAME 属性都设置为了“myField”，则会创建元素为 myField[0]、myField[1] 和 myField[2] 的数组。你需要在代码中注意到这种情况的发生，并且十分清楚 myField 究竟是引用单个元素还是一个元素数组。

示例

在下面的例子中，valueGetter 函数将使用一个 for 循环来遍历 valueTest 表单中的元素数组。msgWindow 窗口将显示表单中所有元素的名称：

newWindow=window.open("http://home.netscape.com")
function valueGetter() {
var msgWindow=window.open("")
for (var i = 0; i < newWindow.document.valueTest.elements.length; i++) {
msgWindow.document.write(newWindow.document.valueTest.elements[i].name + "<BR>")
}
}

参看

Submit.value

type

对于所有的 Submit 对象，属性的值都是“submit”。该属性指定了表单元素的类型。

属性源 | Submit
只读 |
实现版本 | Navigator 3.0

示例

下面的例子将在表单上写出每个元素的 type 属性。

for (var i = 0; i < document.form1.elements.length; i++) {
document.writeln("<BR>type 为 " + document.form1.elements[i].type)
}

value

反映了提交按钮的 VALUE 属性的字符串。

属性源 | Submit
只读 |
实现版本 | Navigator 2.0

安全性

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

描述

如果在 HTML 中指定了 VALUE 属性，value 属性就是在按钮的表面上显示的文本。如果没有在 HTML 中指定 VALUE 属性，该按钮的 value 属性就为字符串“Submit Query”。

不要混淆 value 属性和 name 属性。name 属性不会显示在屏幕上；它只用于编程时对该按钮的引用。

示例

下面的函数将计算一组按钮的 value 属性，并将其显示在 msgWindow 窗口中：

function valueGetter() {
var msgWindow=window.open("")
msgWindow.document.write("submitButton.value 为 " +
document.valueTest.submitButton.value + "<BR>")
msgWindow.document.write("resetButton.value 为 " +
document.valueTest.resetButton.value + "<BR>")
msgWindow.document.write("helpButton.value 为 " +
document.valueTest.helpButton.value + "<BR>")
msgWindow.document.close()
} 这个例子将显示下列值：

Submit Query
Reset
帮助 上面的例子假定如下定义了按钮：

<INPUT TYPE="submit" NAME="submitButton">
<INPUT TYPE="reset" NAME="resetButton">
<INPUT TYPE="button" NAME="helpButton" VALUE="帮助">

参看

Submit.name

方法

blur

 将焦点从提交按钮移开。

方法源 | Submit
实现版本 | Navigator 2.0

语法

blur()

参数

 无

参看

Submit.focus

click

模拟对提交按钮的单击，但不触发对象的 onClick 事件句柄。

方法源 | Submit
实现版本 | Navigator 2.0

语法

click()

参数

 无

focus

将焦点移至提交按钮上。

方法源 | Submit
实现版本 | Navigator 2.0

语法

focus()

参数

 无

参看

Submit.blur

handleEvent

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

方法源 | Submit
实现版本 | Navigator 4.0

语法

handleEvent(event)

参数

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

描述

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


JavaScript语言参考手册_表单

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

Reset

 A reset button on an HTML form. A reset button resets all elements in a form to their defaults.

客户端对象 |
实现版本 | Navigator 2.0 Navigator 3.0: 添加了 type 属性; 添加了 onBlur and onFocus event handlers; 添加了 blur and focus 方法s Navigator 4.0: 添加了 handleEvent 方法。

创建源

The HTML INPUT tag, with "reset" as the value of the TYPE attribute. For a given form, the JavaScript runtime engine creates an appropriate Reset object and puts it in the elements array of the corresponding Form object. You access a Reset object by indexing this array. You can index the array either by number or, if supplied, by using the value of the NAME attribute.

事件句柄

  • onBlur
  • onClick
  • onFocus

描述

 A Reset object on a form looks as follows:

A Reset object is a form element and must be defined within a FORM tag.

The reset button's onClick event handler cannot prevent a form from being reset; once the button is clicked, the reset cannot be canceled.

属性概览

form | Specifies the form containing the Reset object.
name | Reflects the NAME attribute.
type | Reflects the TYPE attribute.
value | Reflects the VALUE attribute.

方法概览

blur | Removes focus from the reset button.
click | Simulates a mouse-click on the reset button.
focus | Gives focus to the reset button.
handleEvent | 调用指定事件的控制句柄。

示例

示例 1. The following example displays a Text object with the default value "CA" and a reset button with the text "Clear Form" displayed on its face. If the user types a state abbreviation in the Text object and then clicks the Clear Form button, the original value of "CA" is restored.

<B>State: </B><INPUT TYPE="text" NAME="state" VALUE="CA" SIZE="2">
<P><INPUT TYPE="reset" VALUE="Clear Form"> 示例 2. The following example displays two Text objects, a Select object, and three radio buttons; all of these objects have default values. The form also has a reset button with the text "Defaults" on its face. If the user changes the value of any of the objects and then clicks the Defaults button, the original values are restored.

<HTML>
<HEAD>
<TITLE>Reset object example</TITLE>
</HEAD>
<BODY>
<FORM NAME="form1">
<BR><B>City: </B><INPUT TYPE="text" NAME="city" VALUE="Santa Cruz" SIZE="20">
<B>State: </B><INPUT TYPE="text" NAME="state" VALUE="CA" SIZE="2">
<P><SELECT NAME="colorChoice">
<OPTION SELECTED> Blue
<OPTION> Yellow
<OPTION> Green
<OPTION> Red
</SELECT>
<P><INPUT TYPE="radio" NAME="musicChoice" VALUE="soul-and-r&b"
CHECKED> Soul and R&B
<BR><INPUT TYPE="radio" NAME="musicChoice" VALUE="jazz">
Jazz
<BR><INPUT TYPE="radio" NAME="musicChoice" VALUE="classical">
Classical
<P><INPUT TYPE="reset" VALUE="Defaults" NAME="reset1">
</FORM>
</BODY>
</HTML>

参看

Button, Form, onReset, Form.reset, Submit

属性

form

 An object reference specifying the form containing the reset button.

属性源 | Reset
只读 |
实现版本 | Navigator 2.0

描述

每个表单元素都有一个 form 属性用于指向元素的父表单。该属性在事件控制句柄中特别有用，你可能想要由其获得当前表单中其它元素。

参看

Form

name

A string specifying the name of the reset button.

属性源 | Reset
实现版本 | Navigator 2.0

安全性

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

描述

The value of the name property initially reflects the value of the NAME attribute. Changing the name property overrides this setting.

Do not confuse the name property with the label displayed on the reset button. The value property specifies the label for this button. The name property is not displayed on the screen; it is used to refer programmatically to the button.

If multiple objects on the same form have the same NAME attribute, an array of the given name is created automatically. Each element in the array represents an individual Form object. Elements are indexed in source order starting at 0. For example, if two Text elements and a Reset element on the same form have their NAME attribute set to "myField", an array with the elements myField[0], myField[1], and myField[2] is created. You need to be aware of this situation in your code and know whether myField refers to a single element or to an array of elements.

示例

In the following example, the valueGetter function uses a for loop to iterate over the array of elements on the valueTest form. The msgWindow window displays the names of all the elements on the form:

newWindow=window.open("http://home.netscape.com")
function valueGetter() {
var msgWindow=window.open("")
for (var i = 0; i < newWindow.document.valueTest.elements.length; i++) {
msgWindow.document.write(newWindow.document.valueTest.elements[i].name + "<BR>")
}
}

参看

Reset.value

type

For all Reset objects, the value of the type property is "reset". This property specifies the form element's type.

属性源 | Reset
只读 |
实现版本 | Navigator 3.0

示例

The following example writes the value of the type property for every element on a form.

for (var i = 0; i < document.form1.elements.length; i++) {
document.writeln("<BR>type is " + document.form1.elements[i].type)
}

value

A string that reflects the reset button's VALUE attribute.

属性源 | Reset
只读 |
实现版本 | Navigator 2.0

安全性

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

描述

This string is displayed on the face of the button. When a VALUE attribute is not specified in HTML, the value property is the string "Reset".

Do not confuse the value property with the name property. The name property is not displayed on the screen; it is used to refer programmatically to the button.

示例

The following function evaluates the value property of a group of buttons and displays it in the msgWindow window:

function valueGetter() {
var msgWindow=window.open("")
msgWindow.document.write("submitButton.value is " +
document.valueTest.submitButton.value + "<BR>")
msgWindow.document.write("resetButton.value is " +
document.valueTest.resetButton.value + "<BR>")
msgWindow.document.write("helpButton.value is " +
document.valueTest.helpButton.value + "<BR>")
msgWindow.document.close()
} This example displays the following values:

Query Submit
Reset
Help The previous example assumes the buttons have been defined as follows:

<INPUT TYPE="submit" NAME="submitButton">
<INPUT TYPE="reset" NAME="resetButton">
<INPUT TYPE="button" NAME="helpButton" VALUE="Help">

参看

Reset.name

方法

blur

 Removes focus from the reset button.

方法源 | Reset
实现版本 | Navigator 2.0

语法

blur()

参数

 无

示例

The following example removes focus from the reset button userReset:

userReset.blur() This example assumes that the button is defined as

<INPUT TYPE="reset" NAME="userReset">

参看

Reset.focus

click

Simulates a mouse-click on the reset button, but does not trigger an object's onClick event handler.

方法源 | Reset
实现版本 | Navigator 2.0

语法

click()

参数

 无

focus

Navigates to the reset button and gives it focus.

方法源 | Reset
实现版本 | Navigator 2.0

语法

focus()

参数

 无

参看

Reset.blur

handleEvent

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

方法源 | Reset
实现版本 | Navigator 4.0

语法

handleEvent(event)

参数

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


JavaScript语言参考手册_表单

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

Radio

 HTML 表单中的一组单选钮中的单个单选钮。用户可以使用一组单选钮用以从一系列选项中选择一个。

客户端对象 |
实现版本 | Navigator 2.0 Navigator 3.0: 添加了 type 属性；添加了 blur 和 focus 方法。 Navigator 4.0: 添加了 handleEvent 方法。

创建源

将 TYPE 属性设定为“radio”的 HTML INPUT 标签可创建本类型的对象。所有位于同一组中的单选钮必须 NAME 属性相同。这将使得它们可以作为一个独立组访问。

对于一个给定的表单，JavaScript 运行时刻引擎将为每个该表单中的单选钮创建一个独立的 Radio 对象。它将所有 NAME 属性相同的 Radio 对象放在一个单独的数组中，然后将那样的数组放在对应的 Form 对象的 elements 数组中。如果单个窗体有多组单选钮，则 elements 数组就有多个 Radio 对象数组。

你可以使用 Form.elements 数组访问一组单选钮(既可以通过编号，也可以通过使用 NAME 属性的值)。要访问一组单选钮中的单个单选钮，你可以使用返回的对象数组。例如，如果你的文档中由一个叫做 emp 的表单，里面有一组 NAME 属性为“dept”的单选钮，你就可以用 document.emp.dept[0]，document.emp.dept[1] 等等这样的形式访问单个单选钮。

事件句柄

  • onBlur
  • onClick
  • onFocus

描述

 表单中的单选钮组看起来与下面的图相似：

一个 Radio 对象是一个表单元素，并且必须在 FORM 标签内定义。

属性概览

checked | 可以让你用程序的方法选择一个单选钮(单个单选钮的属性)。
defaultChecked | 对应于 CHECKED 属性(单个单选钮的属性)。
form | 指定包含该 Radio 对象的表单(单选钮组的属性)。
name | 对应于 NAME 属性(单选钮组的属性)。
type | 对应于 TYPE 属性(单选钮组的属性)。
value | 对应于 VALUE 属性(单选钮组的属性)。

方法概览

blur | 从单选钮上移除焦点。
click | 模拟对单选钮的单击。
focus | 将焦点移至单选钮。
handleEvent | 调用指定事件的控制句柄。

示例

示例 1. 下面的例子中定义了一个单选钮组用于选择三个音乐专辑中的一个。每个单选钮的名称都是相同的，NAME="musicChoice"，它们组成了一组单选钮，其中只有一个可选。这个例子同时定义了一个文本域，其中的文本默认为与单选钮的选项相同，但也可由用户自行输入非标准的专辑名称。onClick 事件控制句柄将在用户单击单选钮时设置专辑名称的输入域。

<INPUT TYPE="text" NAME="catalog" SIZE="20">
<INPUT TYPE="radio" NAME="musicChoice" VALUE="rock"
onClick="musicForm.catalog.value = '摇滚'"> 摇滚
<INPUT TYPE="radio" NAME="musicChoice" VALUE="jazz"
onClick="musicForm.catalog.value = '爵士乐'"> 爵士乐
<INPUT TYPE="radio" NAME="musicChoice" VALUE="classical"
onClick="musicForm.catalog.value = '古典乐'"> 古典乐

示例 2. 下面的例子包含了一个表单，其中有三个文本框和三个单选钮。单选钮允许用户选择是将文本域转换成小写还是大写，或者是不转换。每个文本域的 onChange 事件控制句柄都会根据选择的单选钮转换文本域的值。设置转换成小写和大写的单选钮都有 onClick 事件控制句柄都会在用户单击单选钮时转换所有域。

<HTML>
<HEAD>
<TITLE>Radio 对象示例</TITLE>
</HEAD>
<SCRIPT>
function convertField(field) {
if (document.form1.conversion[0].checked) {
field.value = field.value.toUpperCase()}
else {
if (document.form1.conversion[1].checked) {
field.value = field.value.toLowerCase()}
}
}
function convertAllFields(caseChange) {
if (caseChange=="upper") {
document.form1.lastName.value = document.form1.lastName.value.toUpperCase()
document.form1.firstName.value = document.form1.firstName.value.toUpperCase()
document.form1.cityName.value = document.form1.cityName.value.toUpperCase()}
else {
document.form1.lastName.value = document.form1.lastName.value.toLowerCase()
document.form1.firstName.value = document.form1.firstName.value.toLowerCase()
document.form1.cityName.value = document.form1.cityName.value.toLowerCase()
}
}
</SCRIPT>
<BODY>
<FORM NAME="form1">
<B>姓：</B>
<INPUT TYPE="text" NAME="lastName" SIZE=20 onChange="convertField(this)">
<BR><B>名：</B>
<INPUT TYPE="text" NAME="firstName" SIZE=20 onChange="convertField(this)">
<BR><B>城市：</B>
<INPUT TYPE="text" NAME="cityName" SIZE=20 onChange="convertField(this)">
<P><B>将输入内容转换为：</B>
<BR><INPUT TYPE="radio" NAME="conversion" VALUE="upper"
onClick="if (this.checked) {convertAllFields('upper')}">大写
<BR><INPUT TYPE="radio" NAME="conversion" VALUE="lower"
onClick="if (this.checked) {convertAllFields('lower')}">小写
<BR><INPUT TYPE="radio" NAME="conversion" VALUE="noChange">不做转换
</FORM>
</BODY>
</HTML>
See also the example for Link.

参看

Checkbox, Form, Select

属性

checked

 指定了该单选钮是否选中的 Boolean 值。

属性源 | Radio
实现版本 | Navigator 2.0

安全性

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

描述

If a radio button is selected, the value of its checked property is true; otherwise, it is false. You can set the checked property at any time. The display of the radio button updates immediately when you set the checked property.

At any given time, only one button in a set of radio buttons can be checked. When you set the checked property for one radio button in a group to true, that property for all other buttons in the group becomes false.

示例

The following example examines an array of radio buttons called musicType on the musicForm form to determine which button is selected. The VALUE attribute of the selected button is assigned to the checkedButton variable.

function stateChecker() {
var checkedButton = ""
for (var i in document.musicForm.musicType) {
if (document.musicForm.musicType[i].checked=="1") {
checkedButton=document.musicForm.musicType[i].value
}
}
}

参看

Radio.defaultChecked

defaultChecked

A Boolean value indicating the default selection state of a radio button.

属性源 | Radio
实现版本 | Navigator 2.0

安全性

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

描述

If a radio button is selected by default, the value of the defaultChecked property is true; otherwise, it is false. defaultChecked initially reflects whether the CHECKED attribute is used within an INPUT tag; however, setting defaultChecked overrides the CHECKED attribute.

Unlike for the checked property, changing the value of defaultChecked for one button in a radio group does not change its value for the other buttons in the group.

You can set the defaultChecked property at any time. The display of the radio button does not update when you set the defaultChecked property, only when you set the checked property.

示例

The following example resets an array of radio buttons called musicType on the musicForm form to the default selection state:

function radioResetter() {
var i=""
for (i in document.musicForm.musicType) {
if (document.musicForm.musicType[i].defaultChecked==true) {
document.musicForm.musicType[i].checked=true
}
}
}

参看

Radio.checked

form

An object reference specifying the form containing the radio button.

属性源 | Radio
只读 |
实现版本 | Navigator 2.0

描述

每个表单元素都有一个 form 属性用于指向元素的父表单。该属性在事件控制句柄中特别有用，你可能想要由其获得当前表单中其它元素。

name

A string specifying the name of the set of radio buttons with which this button is associated.

属性源 | Radio
实现版本 | Navigator 2.0

安全性

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

描述

The name property initially reflects the value of the NAME attribute. Changing the name property overrides this setting.

All radio buttons that have the same value for their name property are in the same group and are treated together. If you change the name of a single radio button, you change which group of buttons it belongs to.

Do not confuse the name property with the label displayed on a Button. The value property specifies the label for the button. The name property is not displayed onscreen; it is used to refer programmatically to the button.

示例

In the following example, the valueGetter function uses a for loop to iterate over the array of elements on the valueTest form. The msgWindow window displays the names of all the elements on the form:

newWindow=window.open("http://home.netscape.com")
function valueGetter() {
var msgWindow=window.open("")
for (var i = 0; i < newWindow.document.valueTest.elements.length; i++) {
msgWindow.document.write(newWindow.document.valueTest.elements[i].name + "<BR>")
}
}

type

For all Radio objects, the value of the type property is "radio". This property specifies the form element's type.

属性源 | Radio
只读 |
实现版本 | Navigator 3.0

示例

The following example writes the value of the type property for every element on a form.

for (var i = 0; i < document.form1.elements.length; i++) {
document.writeln("<BR>type is " + document.form1.elements[i].type)
}

value

 A string that reflects the VALUE attribute of the radio button.

属性源 | Radio
只读 |
实现版本 | Navigator 2.0

安全性

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

描述

When a VALUE attribute is specified in HTML, the value property is a string that reflects it. When a VALUE attribute is not specified in HTML, the value property is a string that evaluates to "on". The value property is not displayed on the screen but is returned to the server if the radio button or checkbox is selected.

Do not confuse the property with the selection state of the radio button or the text that is displayed next to the button. The checked property determines the selection state of the object, and the defaultChecked property determines the default selection state. The text that is displayed is specified following the INPUT tag.

示例

The following function evaluates the value property of a group of radio buttons and displays it in the msgWindow window:

function valueGetter() {
var msgWindow=window.open("")
for (var i = 0; i < document.valueTest.radioObj.length; i++) {
msgWindow.document.write
("The value of radioObj[" + i + "] is " +
document.valueTest.radioObj[i].value +"<BR>")
}
msgWindow.document.close()
}
This example displays the following values:

on
on
on
on The previous example assumes the buttons have been defined as follows:

<BR><INPUT TYPE="radio" NAME="radioObj">R&B
<BR><INPUT TYPE="radio" NAME="radioObj" CHECKED>Soul
<BR><INPUT TYPE="radio" NAME="radioObj">Rock and Roll
<BR><INPUT TYPE="radio" NAME="radioObj">Blues

参看

Radio.checked, Radio.defaultChecked

方法

blur

 Removes focus from the radio button.

方法源 | Radio
实现版本 | Navigator 2.0

语法

blur()

参数

 无

参看

Radio.focus

click

Simulates a mouse-click on the radio button, but does not trigger the button's onClick event handler.

方法源 | Radio
实现版本 | Navigator 2.0

语法

click()

参数

 无

示例

The following example toggles the selection status of the first radio button in the musicType Radio object on the musicForm form:

document.musicForm.musicType[0].click() The following example toggles the selection status of the newAge checkbox on the musicForm form:

document.musicForm.newAge.click()

focus

Gives focus to the radio button.

方法源 | Radio
实现版本 | Navigator 2.0

语法

focus()

参数

 无

描述

Use the focus method to navigate to the radio button and give it focus. The user can then easily toggle that button.

参看

Radio.blur

handleEvent

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

方法源 | Radio
实现版本 | Navigator 4.0

语法

handleEvent(event)

参数

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


JavaScript语言参考手册_表单

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

Checkbox

 A checkbox on an HTML form. A checkbox is a toggle switch that lets the user set a value on or off.

客户端对象 |
实现版本 | Navigator 2.0 Navigator 3.0: 添加了 type 属性; 添加了 onBlur and onFocus event handlers; 添加了 blur and focus 方法s. Navigator 4.0: 添加了 handleEvent 方法。

创建源

The HTML INPUT tag, with "checkbox" as the value of the TYPE attribute. For a given form, the JavaScript runtime engine creates appropriate Checkbox objects and puts these objects in the elements array of the corresponding Form object. You access a Checkbox object by indexing this array. You can index the array either by number or, if supplied, by using the value of the NAME attribute.

事件句柄

  • onBlur
  • onClick
  • onFocus

描述

 A Checkbox object on a form looks as follows:

A Checkbox object is a form element and must be defined within a FORM tag.

Use the checked property to specify whether the checkbox is currently checked. Use the defaultChecked property to specify whether the checkbox is checked when the form is loaded or reset.

属性概览

checked | Boolean 属性 that reflects the current state of the checkbox.
defaultChecked | Boolean 属性 that reflects the CHECKED attribute.
form | Specifies the form containing the Checkbox object.
name | Reflects the NAME attribute.
type | Reflects the TYPE attribute.
value | Reflects the TYPE attribute.

方法概览

blur | Removes focus from the checkbox.
click | Simulates a mouse-click on the checkbox.
focus | Gives focus to the checkbox.
handleEvent | 调用指定事件的控制句柄。

示例

示例 1. The following example displays a group of four checkboxes that all appear checked by default:

<B>Specify your music preferences (check all that apply):</B>
<BR><INPUT TYPE="checkbox" NAME="musicpref_rnb" CHECKED> R&B
<BR><INPUT TYPE="checkbox" NAME="musicpref_jazz" CHECKED> Jazz
<BR><INPUT TYPE="checkbox" NAME="musicpref_blues" CHECKED> Blues
<BR><INPUT TYPE="checkbox" NAME="musicpref_newage" CHECKED> New Age
示例 2. The following example contains a form with three text boxes and one checkbox. The user can use the checkbox to choose whether the text fields are converted to uppercase. Each text field has an onChange event handler that converts the field value to uppercase if the checkbox is checked. The checkbox has an onClick event handler that converts all fields to uppercase when the user checks the checkbox.

<HTML>
<HEAD>
<TITLE>Checkbox object example</TITLE>
</HEAD>
<SCRIPT>
function convertField(field) {
if (document.form1.convertUpper.checked) {
field.value = field.value.toUpperCase()}
}
function convertAllFields() {
document.form1.lastName.value = document.form1.lastName.value.toUpperCase()
document.form1.firstName.value = document.form1.firstName.value.toUpperCase()
document.form1.cityName.value = document.form1.cityName.value.toUpperCase()
}
</SCRIPT>
<BODY>
<FORM NAME="form1">
<B>Last name:</B>
<INPUT TYPE="text" NAME="lastName" SIZE=20 onChange="convertField(this)">
<BR><B>First name:</B>
<INPUT TYPE="text" NAME="firstName" SIZE=20 onChange="convertField(this)">
<BR><B>City:</B>
<INPUT TYPE="text" NAME="cityName" SIZE=20 onChange="convertField(this)">
<P><INPUT TYPE="checkBox" NAME="convertUpper"
onClick="if (this.checked) {convertAllFields()}"
> Convert fields to upper case
</FORM>
</BODY>
</HTML>

参看

Form, Radio

属性

checked

 A Boolean value specifying the selection state of the checkbox.

属性源 | Checkbox
实现版本 | Navigator 2.0

安全性

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

描述

If a checkbox button is selected, the value of its checked property is true; otherwise, it is false.

You can set the checked property at any time. The display of the checkbox button updates immediately when you set the checked property.

参看

Checkbox.defaultChecked

defaultChecked

A Boolean value indicating the default selection state of a checkbox button.

属性源 | Checkbox
实现版本 | Navigator 2.0

安全性

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

描述

If a checkbox is selected by default, the value of the defaultChecked property is true; otherwise, it is false. defaultChecked initially reflects whether the CHECKED attribute is used within an INPUT tag; however, setting defaultChecked overrides the CHECKED attribute.

You can set the defaultChecked property at any time. The display of the checkbox does not update when you set the defaultChecked property, only when you set the checked property.

参看

Checkbox.checked

form

An object reference specifying the form containing the checkbox.

属性源 | Checkbox
只读 |
实现版本 | Navigator 2.0

描述

每个表单元素都有一个 form 属性用于指向元素的父表单。该属性在事件控制句柄中特别有用，你可能想要由其获得当前表单中其它元素。

参看

Form

name

A string specifying the checkbox's name.

属性源 | Checkbox
实现版本 | Navigator 2.0

安全性

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

描述

If multiple objects on the same form have the same NAME attribute, an array of the given name is created automatically. Each element in the array represents an individual Form object. Elements are indexed in source order starting at 0. For example, if two Text elements and a Button element on the same form have their NAME attribute set to "myField", an array with the elements myField[0], myField[1], and myField[2] is created. You need to be aware of this situation in your code and know whether myField refers to a single element or to an array of elements.

示例

In the following example, the valueGetter function uses a for loop to iterate over the array of elements on the valueTest form. The msgWindow window displays the names of all the elements on the form:

newWindow=window.open("http://home.netscape.com")
function valueGetter() {
var msgWindow=window.open("")
for (var i = 0; i < newWindow.document.valueTest.elements.length; i++) {
msgWindow.document.write(newWindow.document.valueTest.elements[i].name + "<BR>")
}
}

type

For all Checkbox objects, the value of the type property is "checkbox". This property specifies the form element's type.

属性源 | Checkbox
只读 |
实现版本 | Navigator 3.0

示例

The following example writes the value of the type property for every element on a form.

for (var i = 0; i < document.form1.elements.length; i++) {
document.writeln("<BR>type is " + document.form1.elements[i].type)
}

value

A string that reflects the VALUE attribute of the checkbox.

属性源 | Checkbox
实现版本 | Navigator 2.0

安全性

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

参看

Checkbox.checked, Checkbox.defaultChecked

方法

blur

 Removes focus from the checkbox.

方法源 | Checkbox
实现版本 | Navigator 2.0

语法

blur()

参数

 无

参看

Checkbox.focus

click

Simulates a mouse-click on the checkbox, but does not trigger its onClick event handler. The method checks the checkbox and sets toggles its value.

方法源 | Checkbox
实现版本 | Navigator 2.0

语法

click()

参数

 无。

示例

The following example toggles the selection status of the newAge checkbox on the musicForm form:

document.musicForm.newAge.click()

focus

Gives focus to the checkbox.

方法源 | Checkbox
实现版本 | Navigator 2.0

语法

focus()

参数

 无

描述

Use the focus method to navigate to a the checkbox and give it focus. The user can then toggle the state of the checkbox.

参看

Checkbox.blur

handleEvent

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

方法源 | Checkbox
实现版本 | Navigator 4.0

语法

handleEvent(event)

参数

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


JavaScript语言参考手册_表单

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

Select

 A selection list on an HTML form. The user can choose one or more items from a selection list, depending on how the list was created.

客户端对象 |
实现版本 | Navigator 2.0 Navigator 3.0: 添加了 type 属性; 添加了 the ability to add and delete options. Navigator 4.0: 添加了 handleEvent 方法。

创建源

The HTML SELECT tag. For a given form, the JavaScript runtime engine creates appropriate Select objects for each selection list and puts these objects in the elements array of the corresponding Form object. You access a Select object by indexing this array. You can index the array either by number or, if supplied, by using the value of the NAME attribute.

The runtime engine also creates Option objects for each OPTION tag inside the SELECT tag.

事件句柄

  • onBlur
  • onChange
  • onFocus

描述

 The following figure shows a form containing two selection lists. The user can choose one item from the list on the left and can choose multiple items from the list on the right:

A Select object is a form element and must be defined within a FORM tag.

属性概览

form | Specifies the form containing the selection list.
length | Reflects the number of options in the selection list.
name | Reflects the NAME attribute.
options | Reflects the OPTION tags.
selectedIndex | Reflects the index of the selected option (or the first selected option, if multiple options are selected).
type | Specifies that the object is represents a selection list and whether it can have one or more selected options.

方法概览

blur | Removes focus from the selection list.
focus | Gives focus to the selection list.
handleEvent | 调用指定事件的控制句柄。

示例

示例 1. The following example displays two selection lists. In the first list, the user can select only one item; in the second list, the user can select multiple items.

Choose the music type for your free CD:
<SELECT NAME="music_type_single">
<OPTION SELECTED> R&B
<OPTION> Jazz
<OPTION> Blues
<OPTION> New Age
</SELECT>
<P>Choose the music types for your free CDs:
<BR><SELECT NAME="music_type_multi" MULTIPLE>
<OPTION SELECTED> R&B
<OPTION> Jazz
<OPTION> Blues
<OPTION> New Age
</SELECT> 示例 2. The following example displays two selection lists that let the user choose a month and day. These selection lists are initialized to the current date. The user can change the month and day by using the selection lists or by choosing preset dates from radio buttons. Text fields on the form display the values of the Select object's properties and indicate the date chosen and whether it is Cinco de Mayo.

<HTML>
<HEAD>
<TITLE>Select object example</TITLE>
</HEAD>
<BODY>
<SCRIPT>
var today = new Date()
//---------------
function updatePropertyDisplay(monthObj,dayObj) {
// Get date strings
var monthInteger, dayInteger, monthString, dayString
monthInteger=monthObj.selectedIndex
dayInteger=dayObj.selectedIndex
monthString=monthObj.options[monthInteger].text
dayString=dayObj.options[dayInteger].text
// Display property values
document.selectForm.textFullDate.value=monthString + " " + dayString
document.selectForm.textMonthLength.value=monthObj.length
document.selectForm.textDayLength.value=dayObj.length
document.selectForm.textMonthName.value=monthObj.name
document.selectForm.textDayName.value=dayObj.name
document.selectForm.textMonthIndex.value=monthObj.selectedIndex
document.selectForm.textDayIndex.value=dayObj.selectedIndex
// Is it Cinco de Mayo?
if (monthObj.options[4].selected && dayObj.options[4].selected)
document.selectForm.textCinco.value="Yes!"
else
document.selectForm.textCinco.value="No"
}
</SCRIPT>
<!--------------->
<FORM NAME="selectForm">
<P><B>Choose a month and day:</B>
Month: <SELECT NAME="monthSelection"
onChange="updatePropertyDisplay(this,document.selectForm.daySelection)">
<OPTION> January <OPTION> February <OPTION> March
<OPTION> April <OPTION> May <OPTION> June
<OPTION> July <OPTION> August <OPTION> September
<OPTION> October <OPTION> November <OPTION> December
</SELECT>
Day: <SELECT NAME="daySelection"
onChange="updatePropertyDisplay(document.selectForm.monthSelection,this)">
<OPTION> 1 <OPTION> 2 <OPTION> 3 <OPTION> 4 <OPTION> 5
<OPTION> 6 <OPTION> 7 <OPTION> 8 <OPTION> 9 <OPTION> 10
<OPTION> 11 <OPTION> 12 <OPTION> 13 <OPTION> 14 <OPTION> 15
<OPTION> 16 <OPTION> 17 <OPTION> 18 <OPTION> 19 <OPTION> 20
<OPTION> 21 <OPTION> 22 <OPTION> 23 <OPTION> 24 <OPTION> 25
<OPTION> 26 <OPTION> 27 <OPTION> 28 <OPTION> 29 <OPTION> 30
<OPTION> 31
</SELECT>
<P><B>Set the date to: </B>
<INPUT TYPE="radio" NAME="dateChoice"
onClick="
monthSelection.selectedIndex=0;
daySelection.selectedIndex=0;
updatePropertyDisplay
document.selectForm.monthSelection,document.selectForm.daySelection)">
New Year's Day
<INPUT TYPE="radio" NAME="dateChoice"
onClick="
monthSelection.selectedIndex=4;
daySelection.selectedIndex=4;
updatePropertyDisplay
(document.selectForm.monthSelection,document.selectForm.daySelection)">
Cinco de Mayo
<INPUT TYPE="radio" NAME="dateChoice"
onClick="
monthSelection.selectedIndex=5;
daySelection.selectedIndex=20;
updatePropertyDisplay
(document.selectForm.monthSelection,document.selectForm.daySelection)">
Summer Solstice
<P><B>Property values:</B>
<BR>Date chosen: <INPUT TYPE="text" NAME="textFullDate" VALUE="" SIZE=20">
<BR>monthSelection.length<INPUT TYPE="text" NAME="textMonthLength" VALUE="" SIZE=20">
<BR>daySelection.length<INPUT TYPE="text" NAME="textDayLength" VALUE="" SIZE=20">
<BR>monthSelection.name<INPUT TYPE="text" NAME="textMonthName" VALUE="" SIZE=20">
<BR>daySelection.name<INPUT TYPE="text" NAME="textDayName" VALUE="" SIZE=20">
<BR>monthSelection.selectedIndex
<INPUT TYPE="text" NAME="textMonthIndex" VALUE="" SIZE=20">
<BR>daySelection.selectedIndex<INPUT TYPE="text" NAME="textDayIndex" VALUE="" SIZE=20">
<BR>Is it Cinco de Mayo? <INPUT TYPE="text" NAME="textCinco" VALUE="" SIZE=20">
<SCRIPT>
document.selectForm.monthSelection.selectedIndex=today.getMonth()
document.selectForm.daySelection.selectedIndex=today.getDate()-1
updatePropertyDisplay(document.selectForm.monthSelection,document.selectForm.daySelection)
</SCRIPT>
</FORM>
</BODY>
</HTML> 示例 3. Add an option with the Option constructor. The following example creates two Select objects, one with and one without the MULTIPLE attribute. No options are initially defined for either object. When the user clicks a button associated with the Select object, the populate function creates four options for the Select object and selects the first option.

<SCRIPT>
function populate(inForm) {
colorArray = new Array("Red", "Blue", "Yellow", "Green")
   var option0 = new Option("Red", "color_red")
var option1 = new Option("Blue", "color_blue")
var option2 = new Option("Yellow", "color_yellow")
var option3 = new Option("Green", "color_green")
   for (var i=0; i < 4; i++) {
eval("inForm.selectTest.options[i]=option" + i)
if (i==0) {
inForm.selectTest.options[i].selected=true
}
}
   history.go(0)
}
</SCRIPT>
<H3>Select Option() constructor</H3>
<FORM>
<SELECT NAME="selectTest"></SELECT><P>
<INPUT TYPE="button" VALUE="Populate Select List" onClick="populate(this.form)">
<P>
</FORM>
<HR>
<H3>Select-Multiple Option() constructor</H3>
<FORM>
<SELECT NAME="selectTest" multiple></SELECT><P>
<INPUT TYPE="button" VALUE="Populate Select List" onClick="populate(this.form)">
</FORM>
示例 4. Delete an option. The following function removes an option from a Select object.

function deleteAnItem(theList,itemNo) {
theList.options[itemNo]=null
history.go(0)
}

参看

Form, Radio

属性

form

 An object reference specifying the form containing the selection list.

属性源 | Select
只读 |
实现版本 | Navigator 2.0

描述

每个表单元素都有一个 form 属性用于指向元素的父表单。该属性在事件控制句柄中特别有用，你可能想要由其获得当前表单中其它元素。

参看

Form

length

The number of options in the selection list.

属性源 | Select
只读 |
实现版本 | Navigator 2.0

name

A string specifying the name of the selection list.

属性源 | Select
实现版本 | Navigator 2.0

安全性

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

描述

The name property initially reflects the value of the NAME attribute. Changing the name property overrides this setting. The name property is not displayed on the screen; it is used to refer to the list programmatically.

If multiple objects on the same form have the same NAME attribute, an array of the given name is created automatically. Each element in the array represents an individual Form object. Elements are indexed in source order starting at 0. For example, if two Text elements and a Select element on the same form have their NAME attribute set to "myField", an array with the elements myField[0], myField[1], and myField[2] is created. You need to be aware of this situation in your code and know whether myField refers to a single element or to an array of elements.

示例

In the following example, the valueGetter function uses a for loop to iterate over the array of elements on the valueTest form. The msgWindow window displays the names of all the elements on the form:

newWindow=window.open("http://home.netscape.com")
function valueGetter() {
var msgWindow=window.open("")
for (var i = 0; i < newWindow.document.valueTest.elements.length; i++) {
msgWindow.document.write(newWindow.document.valueTest.elements[i].name + "<BR>")
}
}

options

An array corresponding to options in a Select object in source order.

属性源 | Select
只读 |
实现版本 | Navigator 2.0

描述

You can refer to the options of a Select object by using the options array. This array contains an entry for each option in a Select object (OPTION tag) in source order. For example, if a Select object named musicStyle contains three options, you can access these options as musicStyle.options[0], musicStyle.options[1], and musicStyle.options[2].

To obtain the number of options in the selection list, you can use either Select.length or the length property of the options array. For example, you can get the number of options in the musicStyle selection list with either of these expressions:

musicStyle.length
musicStyle.options.length You can add or remove options from a selection list using this array. To add or replace an option to an existing Select object, you assign a new Option object to a place in the array. For example, to create a new Option object called jeans and add it to the end of the selection list named myList, you could use this code:

jeans = new Option("Blue Jeans", "jeans", false, false);
myList.options[myList.length] = jeans; To delete an option from a Select object, you set the appropriate index of the options array to null. Removing an option compresses the options array. For example, assume that myList has 5 elements in it, the value of the fourth element is "foo", and you execute this statement:

myList.options[1] = null Now, myList has 4 elements in it and the value of the third element is "foo".

After you delete an option, you must refresh the document by using history.go(0). This statement must be last. When the document reloads, variables are lost if not saved in cookies or form element values.

You can determine which option in a selection list is currently selected by using either the selectedIndex property of the options array or of the Select object itself. That is, the following expressions return the same value:

musicStyle.selectedIndex
musicStyle.options.selectedIndex For more information about this property, see Select.selectedIndex.

For Select objects that can have multiple selections (that is, the SELECT tag has the MULTIPLE attribute), the selectedIndex property is not very useful. In this case, it returns the index of the first selection. To find all the selected options, you have to loop and test each option individually. For example, to print a list of all selected options in a selection list named mySelect, you could use code such as this:

document.write("You've selected the following options:\n")
for (var i = 0; i < mySelect.options.length; i++) {
if (mySelect.options[i].selected)
document.write(" mySelect.options[i].text\n")
}
In general, to work with individual options in a selection list, you work with the appropriate Option object.

selectedIndex

An integer specifying the index of the selected option in a Select object.

属性源 | Select
实现版本 | Navigator 2.0

安全性

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

描述

Options in a Select object are indexed in the order in which they are defined, starting with an index of 0. You can set the selectedIndex property at any time. The display of the Select object updates immediately when you set the selectedIndex property.

If no option is selected, selectedIndex has a value of -1.

In general, the selectedIndex property is more useful for Select objects that are created without the MULTIPLE attribute. If you evaluate selectedIndex when multiple options are selected, the selectedIndex property specifies the index of the first option only. Setting selectedIndex clears any other options that are selected in the Select object.

The Option.selected property is more useful in conjunction with Select objects that are created with the MULTIPLE attribute. With the Option.selected property, you can evaluate every option in the options array to determine multiple selections, and you can select individual options without clearing the selection of other options.

示例

In the following example, the getSelectedIndex function returns the selected index in the musicType Select object:

function getSelectedIndex() {
return document.musicForm.musicType.selectedIndex
} The previous example assumes that the Select object is similar to the following:

<SELECT NAME="musicType">
<OPTION SELECTED> R&B
<OPTION> Jazz
<OPTION> Blues
<OPTION> New Age
</SELECT>

参看

Option.defaultSelected, Option.selected

type

For all Select objects created with the MULTIPLE keyword, the value of the type property is "select-multiple". For Select objects created without this keyword, the value of the type property is "select-one". This property specifies the form element's type.

属性源 | Select
只读 |
实现版本 | Navigator 3.0

示例

The following example writes the value of the type property for every element on a form.

for (var i = 0; i < document.form1.elements.length; i++) {
document.writeln("<BR>type is " + document.form1.elements[i].type)
}

方法

blur

 Removes focus from the selection list.

方法源 | Select
实现版本 | Navigator 2.0

语法

blur()

参数

 无

参看

Select.focus

focus

Navigates to the selection list and gives it focus.

方法源 | Select
实现版本 | Navigator 2.0

语法

focus()

参数

 无

描述

Use the focus method to navigate to a selection list and give it focus. The user can then make selections from the list.

参看

Select.blur

handleEvent

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

方法源 | Select
实现版本 | Navigator 4.0

语法

handleEvent(event)

参数

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


JavaScript语言参考手册_表单

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

Option

 An option in a selection list.

客户端对象 |
实现版本 | Navigator 2.0 Navigator 3.0: 添加了 defaultSelected 属性; text 属性 can be changed to change the text of an option

创建源

The Option constructor or the HTML OPTION tag. To create an Option object with its constructor:

new Option(text, value, defaultSelected, selected) Once you've created an Option object, you can add it to a selection list using the Select.options array.

参数

text | (Optional) Specifies the text to display in the select list.
value | (Optional) Specifies a value that is returned to the server when the option is selected and the form is submitted.
defaultSelected | (Optional) Specifies whether the option is initially selected (true or false).
selected | (Optional) Specifies the current selection state of the option (true or false).

属性概览

defaultSelected | Specifies the initial selection state of the option
selected | Specifies the current selection state of the option
text | Specifies the text for the option
value | Specifies the value that is returned to the server when the option is selected and the form is submitted

描述

Usually you work with Option objects in the context of a selection list (a Select object). When JavaScript creates a Select object for each SELECT tag in the document, it creates Option objects for the OPTION tags inside the SELECT tag and puts those objects in the options array of the Select object.

In addition, you can create new options using the Option constructor and add those to a selection list. After you create an option and add it to the Select object, you must refresh the document by using history.go(0). This statement must be last. When the document reloads, variables are lost if not saved in cookies or form element values.

You can use the Option.selected and Select.selectedIndex properties to change the selection state of an option.

  • The Select.selectedIndex property is an integer specifying the index of the selected option. This is most useful for Select objects that are created without the MULTIPLE attribute. The following statement sets a Select object's selectedIndex property:
    • document.myForm.musicTypes.selectedIndex = i

  • The Option.selected property is a Boolean value specifying the current selection state of the option in a Select object. If an option is selected, its selected property is true; otherwise it is false. This is more useful for Select objects that are created with the MULTIPLE attribute. The following statement sets an option's selected property to true:
    • document.myForm.musicTypes.options[i].selected = true
To change an option's text, use is Option.text property. For example, suppose a form has the following Select object:

<SELECT name="userChoice">
<OPTION>Choice 1
<OPTION>Choice 2
<OPTION>Choice 3
</SELECT> You can set the text of the ith item in the selection based on text entered in a text field named whatsNew as follows:

myform.userChoice.options[i].text = myform.whatsNew.value You do not need to reload or refresh after changing an option's text.

示例

The following example creates two Select objects, one with and one without the MULTIPLE attribute. No options are initially defined for either object. When the user clicks a button associated with the Select object, the populate function creates four options for the Select object and selects the first option.

<SCRIPT>
function populate(inForm) {
colorArray = new Array("Red", "Blue", "Yellow", "Green")
   var option0 = new Option("Red", "color_red")
var option1 = new Option("Blue", "color_blue")
var option2 = new Option("Yellow", "color_yellow")
var option3 = new Option("Green", "color_green")
   for (var i=0; i < 4; i++) {
eval("inForm.selectTest.options[i]=option" + i)
if (i==0) {
inForm.selectTest.options[i].selected=true
}
}
   history.go(0)
}
</SCRIPT>
<H3>Select Option() constructor</H3>
<FORM>
<SELECT NAME="selectTest"></SELECT><P>
<INPUT TYPE="button" VALUE="Populate Select List" onClick="populate(this.form)">
<P>
</FORM>
<HR>
<H3>Select-Multiple Option() constructor</H3>
<FORM>
<SELECT NAME="selectTest" multiple></SELECT><P>
<INPUT TYPE="button" VALUE="Populate Select List" onClick="populate(this.form)">
</FORM>

属性

defaultSelected

 A Boolean value indicating the default selection state of an option in a selection list.

属性源 | Option
实现版本 | Navigator 3.0

安全性

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

描述

If an option is selected by default, the value of the defaultSelected property is true; otherwise, it is false. defaultSelected initially reflects whether the SELECTED attribute is used within an OPTION tag; however, setting defaultSelected overrides the SELECTED attribute.

You can set the defaultSelected property at any time. The display of the corresponding Select object does not update when you set the defaultSelected property of an option, only when you set the Option.selected or Select.selectedIndex properties.

A Select object created without the MULTIPLE attribute can have only one option selected by default. When you set defaultSelected in such an object, any previous default selections, including defaults set with the SELECTED attribute, are cleared. If you set defaultSelected in a Select object created with the MULTIPLE attribute, previous default selections are not affected.

示例

In the following example, the restoreDefault function returns the musicType Select object to its default state. The for loop uses the options array to evaluate every option in the Select object. The if statement sets the selected property if defaultSelected is true.

function restoreDefault() {
for (var i = 0; i < document.musicForm.musicType.length; i++) {
if (document.musicForm.musicType.options[i].defaultSelected == true) {
document.musicForm.musicType.options[i].selected=true
}
}
}
The previous example assumes that the Select object is similar to the following:

<SELECT NAME="musicType">
<OPTION SELECTED> R&B
<OPTION> Jazz
<OPTION> Blues
<OPTION> New Age
</SELECT>

参看

Option.selected, Select.selectedIndex

selected

A Boolean value indicating whether an option in a Select object is selected.

属性源 | Option
实现版本 | Navigator 2.0

安全性

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

描述

If an option in a Select object is selected, the value of its selected property is true; otherwise, it is false. You can set the selected property at any time. The display of the associated Select object updates immediately when you set the selected property for one of its options.

In general, the Option.selected property is more useful than the Select.selectedIndex property for Select objects that are created with the MULTIPLE attribute. With the Option.selected property, you can evaluate every option in the Select.options array to determine multiple selections, and you can select individual options without clearing the selection of other options.

示例

See the示例 for defaultSelected.

参看

Option.defaultSelected, Select.selectedIndex

text

A string specifying the text of an option in a selection list.

属性源 | Option
实现版本 | Navigator 2.0 Navigator 3.0: The text 属性 can be changed to updated the selection option. In previous releases, you could set the text 属性 but the new value was not reflected in the Select object.

安全性

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

描述

The text property initially reflects the text that follows an OPTION tag of a SELECT tag. You can set the text property at any time and the text displayed by the option in the selection list changes.

示例

示例 1. In the following example, the getChoice function returns the value of the text property for the selected option. The for loop evaluates every option in the musicType Select object. The if statement finds the option that is selected.

function getChoice() {
for (var i = 0; i < document.musicForm.musicType.length; i++) {
if (document.musicForm.musicType.options[i].selected == true) {
return document.musicForm.musicType.options[i].text
}
}
return null
}
The previous example assumes that the Select object is similar to the following:

<SELECT NAME="musicType">
<OPTION SELECTED> R&B
<OPTION> Jazz
<OPTION> Blues
<OPTION> New Age
</SELECT> 示例 2. In the following form, the user can enter some text in the first text field and then enter a number between 0 and 2 (inclusive) in the second text field. When the user clicks the button, the text is substituted for the indicated option number and that option is selected.

The code for this example looks as follows:

<SCRIPT>
function updateList(theForm, i) {
theForm.userChoice.options[i].text = theForm.whatsNew.value
theForm.userChoice.options[i].selected = true
}
</SCRIPT>
<FORM>
<SELECT name="userChoice">
<OPTION>Choice 1
<OPTION>Choice 2
<OPTION>Choice 3
</SELECT>
<BR>
New text for the option: <INPUT TYPE="text" NAME="whatsNew">
<BR>
Option to change (0, 1, or 2): <INPUT TYPE="text" NAME="idx">
<BR>
<INPUT TYPE="button" VALUE="Change Selection"
onClick="updateList(this.form, this.form.idx.value)">
</FORM>

参看

getOptionValue

value

A string that reflects the VALUE attribute of the option.

属性源 | Option
只读 |
实现版本 | Navigator 2.0

安全性

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

描述

When a VALUE attribute is specified in HTML, the value property is a string that reflects it. When a VALUE attribute is not specified in HTML, the value property is the empty string. The value property is not displayed on the screen but is returned to the server if the option is selected.

Do not confuse the property with the selection state of the option or the text that is displayed next to it. The selected property determines the selection state of the object, and the defaultSelected property determines the default selection state. The text that is displayed is specified following the OPTION tag and corresponds to the text property.

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


JavaScript语言参考手册_版权

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

【目录】 【索引】

版权

Netscape Communications Corporation ("Netscape") and its licensors retain all ownership rights to this document (the "Document"). Use of the Document is governed by applicable copyright law. Netscape may revise this Document from time to time without notice.

THIS DOCUMENT IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN NO EVENT SHALL NETSCAPE BE LIABLE FOR ANY LOSS OF PROFITS, LOSS OF BUSINESS, LOSS OF USE OR DATA, INTERRUPTION OF BUSINESS, OR FOR INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY KIND, ARISING FROM ANY ERROR IN THIS DOCUMENT.

The Document is copyright © 1997 Netscape Communications Corporation. All rights reserved.

The Software includes encryption software from RSA Data Security, Inc. Copyright © 1994, 1995 RSA Data Security, Inc. All rights reserved. Portions of the Software include technology used under license from Verity, Inc. and are copyrighted. Portions of the Software copyright © 1994, 1995 Sun Microsystems, Inc. All rights reserved. Portions of the Software copyright © 1995 PEER Networks, Inc. All rights reserved. Portions of the Software copyright © 1996 Mortice Kern Systems, Inc. All rights reserved. The portion of the Software that provides the DBM function is copyright (c) 1990, 1993, 1994 The Regents of the University of California. All rights reserved. This code is derived from software contributed to Berkeley by Margo Seltzer. Redistribution and use in source and binary forms of the DBM code, with or without modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

3. All advertising materials mentioning features or use of this software must display the following acknowledgement:

This product includes software developed by the University of California, Berkeley and its contributors.

4. Neither the name of the University nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THE SOFTWARE WHICH PROVIDES THE DBM FUNCTION IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Netscape and Netscape Navigator are registered trademarks of Netscape Communications Corporation in the United States and other countries. Netscape's logos and Netscape product and service names are also trademarks of Netscape Communications Corporation, which may be registered in other countries. Other product and brand names are trademarks of their respective owners.

The downloading, export or reexport of Netscape software or any underlying information or technology must be in full compliance with all United States and other applicable laws and regulations. Any provision of Netscape software or documentation to the U.S. Government is with restricted rights as described in the license agreement accompanying Netscape software.

【目录】 【索引】


JavaScript语言参考手册_核心

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

第四章
核心

本章包含了以下 JavaScript 核心对象 Array, Boolean, Date, Function, Math, Number, Object 和 String。这些对象同时适用于客户端和服务器端 JavaScript。

表 4.1 本章用到的对象总览。

表 4.1 核心对象
对象 | 描述
Array | 表述数组。
Boolean | 表述布尔值。
Date | 表述日期。
Function | 指定了一个可编译为函数的字符串 JavaScript 代码。
Math | 提供了基本的数学常量和函数；如其 PI 属性包含了π的值。
Number | 表述实数数值。
Object | 包含了由所有 JavaScript 对象共享的基本功能。
RegExp | 表述了一个正则表达式；同时包含了由所有正则表达式对象的共享的静态属性。
String | 表述了一个 JavaScript 字符串。

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


JavaScript语言参考手册_核心

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

Array

 Represents an array of elements.

Core object
实现版本Navigator 3.0, LiveWire 1.0

创建源

The Array object constructor:

new Array(arrayLength);
new Array(element0, element1, ..., elementN);

参数

arrayLength | (Optional) The initial length of the array. You can access this value using the length 属性.
elementN | (Optional) A list of values for the array's elements. When this form is specified, the array is initialized with the specified values as its elements, and the array's length 属性 is set to the number of arguments.

描述

In Navigator 3.0, you can specify an initial length when you create the array. The following code creates an array of five elements:

billingMethod = new Array(5) When you create an array, all of its elements are initially null. The following code creates an array of 25 elements, then assigns values to the first three elements:

musicTypes = new Array(25)
musicTypes[0] = "R&B"
musicTypes[1] = "Blues"
musicTypes[2] = "Jazz"
However, in Navigator 4.0, if you specify LANGUAGE="JavaScript1.2" in the <SCRIPT> tag, using new Array(1) creates a new array with a[0]=1.

An array's length increases if you assign a value to an element higher than the current length of the array. The following code creates an array of length 0, then assigns a value to element 99. This changes the length of the array to 100.

colors = new Array()
colors[99] = "midnightblue" You can construct a dense array of two or more elements starting with index 0 if you define initial values for all elements. A dense array is one in which each element has a value. The following code creates a dense array with three elements:

myArray = new Array("Hello", myVar, 3.14159) In Navigator 2.0, you must index an array by its ordinal number, for example document.forms[0]. In Navigator 3.0 and later, you can index an array by either its ordinal number or by its name (if defined). For example, assume you define the following array:

myArray = new Array("Wind","Rain","Fire") You can then refer to the first element of the array as myArray[0] or myArray["Wind"].

In Navigator 4.0, the result of a match between a regular expression and a string can create an array. This array has properties and elements that provide information about the match. An array is the return value of RegExp.exec, String.match, and String.replace. To help explain these properties and elements, look at the following example and then refer to the 表 below:

<SCRIPT LANGUAGE="JavaScript1.2">
//Match one d followed by one or more b's followed by one d
//Remember matched b's and the following d
//Ignore case
myRe=/d(b+)(d)/i;
myArray = myRe.exec("cdbBdbsbz");
</SCRIPT>
The properties and elements returned from this match are as follows:

Property/Element | 描述 | Example
input | A 只读 属性 that reflects the original string against which the regular expression was matched. | cdbBdbsbz
index | A 只读 属性 that is the zero-based index of the match in the string. | 1
[0] | A 只读 element that specifies the last matched characters. | dbBd
[1], ...[n] | 只读 elements that specify the parenthesized substring matches, if included in the regular expression. The number of possible parenthesized substrings is unlimited. | [1]=bB [2]=d

属性概览

index | For an array created by a regular expression match, the zero-based index of the match in the string.
input | For an array created by a regular expression match, reflects the original string against which the regular expression was matched.
length | Reflects the number of elements in an array
prototype | Allows the addition of properties to an Array object.

方法概览

concat | Joins two arrays and returns a new array.
join | Joins all elements of an array into a string.
pop | Removes the last element from an array and returns that element.
push | Adds one or more elements to the end of an array and returns that last element added.
reverse | Transposes the elements of an array: the first array element becomes the last and the last becomes the first.
shift | Removes the first element from an array and returns that element
slice | Extracts a section of an array and returns a new array.
splice | Adds and/or removes elements from an array.
sort | Sorts the elements of an array.
toString | Returns a string representing the specified object.
unshift | Adds one or more elements to the front of an array and returns the new length of the array.

示例

示例 1. The following example creates an array, msgArray, with a length of 0, then assigns values to msgArray[0] and msgArray[99], changing the length of the array to 100.

msgArray = new Array()
msgArray [0] = "Hello"
msgArray [99] = "world"
// The following statement is true,
// because defined msgArray [99] element.
if (msgArray .length == 100)
document.write("The length is 100.")
See also示例 for onError.

示例 2: Two-dimensional array. The following code creates a two-dimensional array and displays the results.

a = new Array(4)
for (i=0; i < 4; i++) {
a[i] = new Array(4)
for (j=0; j < 4; j++) {
a[i][j] = "["+i+","+j+"]"
}
}
for (i=0; i < 4; i++) {
str = "Row "+i+":"
for (j=0; j < 4; j++) {
str += a[i][j]
}
document.write(str,"<p>")
}
This example displays the following results:

Multidimensional array test
Row 0:[0,0][0,1][0,2][0,3]
Row 1:[1,0][1,1][1,2][1,3]
Row 2:[2,0][2,1][2,2][2,3]
Row 3:[3,0][3,1][3,2][3,3]

参看

Image

属性

index

 For an array created by a regular expression match, the zero-based index of the match in the string.

属性源 | Array
静态
实现版本 | Navigator 4.0, Netscape Server 3.0

input

For an array created by a regular expression match, reflects the original string against which the regular expression was matched.

属性源 | Array
静态
实现版本 | Navigator 4.0, Netscape Server 3.0

length

An integer that specifies the number of elements in an array. You can set the length property to truncate an array at any time. You cannot extend an array; for example, if you set length to 3 when it is currently 2, the array will still contain only 2 elements.

属性源 | Array
实现版本 | Navigator 3.0, LiveWire 1.0

示例

In the following example, the getChoice function uses the length property to iterate over every element in the musicType array. musicType is a select element on the musicForm form.

function getChoice() {
for (var i = 0; i < document.musicForm.musicType.length; i++) {
if (document.musicForm.musicType.options[i].selected == true) {
return document.musicForm.musicType.options[i].text
}
}
}
The following example shortens the array statesUS to a length of 50 if the current length is greater than 50.

if (statesUS.length > 50) {
statesUS.length=50
alert("The U.S. has only 50 states. New length is " + statesUS.length)
}

prototype

Represents the prototype for this class. You can use the prototype to add properties or methods to all instances of a class. For information on prototypes, see Function.prototype.

属性源 | Array
实现版本 | Navigator 3.0, LiveWire 1.0

方法

concat

 Joins two arrays and returns a new array.

方法源 | Array
实现版本 | Navigator 4.0, Netscape Server 3.0

语法

concat(arrayName2)

参数

arrayName2Name of the array to concatenate to this array.

描述

concat does not alter the original arrays, but returns a "one level deep" copy that contains copies of the same elements combined from the original arrays. Elements of the original arrays are copied into the new array as follows:

  • Object references (and not the actual object) -- concat copies object references into the new array. Both the original and new array refer to the same object. If a referenced object changes, the changes are visible to both the new and original arrays.

  • Strings and numbers (not String and Number objects)-- concat copies strings and numbers into the new array. Changes to the string or number in one array does not affect the other arrays.
If a new element is added to either array, the other array is not affected.

join

Joins all elements of an array into a string.

方法源 | Array
实现版本 | Navigator 3.0, LiveWire 1.0

语法

join(separator)

参数

separatorSpecifies a string to separate each element of the array. The separator is converted to a string if necessary. If omitted, the array elements are separated with a comma.

描述

The string conversion of all array elements are joined into one string.

示例

The following example creates an array, a with three elements, then joins the array three times: using the default separator, then a comma and a space, and then a plus.

a = new Array("Wind","Rain","Fire")
document.write(a.join() +"<BR>")
document.write(a.join(", ") +"<BR>")
document.write(a.join(" + ") +"<BR>")
This code produces the following output:

Wind,Rain,Fire
Wind, Rain, Fire
Wind + Rain + Fire

参看

Array.reverse

pop

Removes the last element from an array and returns that element. This method changes the length of the array.

方法源 | Array
实现版本 | Navigator 4.0, Netscape Server 3.0

语法

pop()

参数

 无。

示例

The following code displays the myFish array before and after removing its last element. It also displays the removed element:

myFish = ["angel", "clown", "mandarin", "surgeon"];
document.writeln("myFish before: " + myFish);
popped = myFish.pop();
document.writeln("myFish after: " + myFish);
document.writeln("popped this element: " + popped);
This example displays the following:

myFish before: ["angel", "clown", "mandarin", "surgeon"]
myFish after: ["angel", "clown", "mandarin"]
popped this element: surgeon

参看

push, shift, unshift

push

Adds one or more elements to the end of an array and returns that last element added. This method changes the length of the array.

方法源 | Array
实现版本 | Navigator 4.0, Netscape Server 3.0

语法

push(elt1, ..., eltN)

参数

elt1, ..., eltNThe elements to add to the end of the array.

描述

The behavior of the push method is analogous to the push function in Perl 4. Note that this behavior is different in Perl 5.

示例

The following code displays the myFish array before and after adding elements to its end. It also displays the last element added:

myFish = ["angel", "clown"];
document.writeln("myFish before: " + myFish);
pushed = myFish.push("drum", "lion");
document.writeln("myFish after: " + myFish);
document.writeln("pushed this element last: " + pushed);
This example displays the following:

myFish before: ["angel", "clown"]
myFish after: ["angel", "clown", "drum", "lion"]
pushed this element last: lion

参看

pop, shift, unshift

reverse

Transposes the elements of an array: the first array element becomes the last and the last becomes the first.

方法源 | Array
实现版本 | Navigator 3.0, LiveWire 1.0

语法

reverse()

参数

 无

描述

The reverse method transposes the elements of the calling array object.

示例

The following example creates an array myArray, containing three elements, then reverses the array.

myArray = new Array("one", "two", "three")
myArray.reverse() This code changes myArray so that:

  • myArray[0] is "three"
    •
  • myArray[1] is "two"
    •
  • myArray[2] is "one"

参看

 Array.join, Array.sort

shift

Removes the first element from an array and returns that element. This method changes the length of the array.

方法源 | Array
实现版本 | Navigator 4.0, Netscape Server 3.0

语法

shift()

参数

 无。

示例

The following code displays the myFish array before and after removing its first element. It also displays the removed element:

myFish = ["angel", "clown", "mandarin", "surgeon"];
document.writeln("myFish before: " + myFish);
shifted = myFish.shift();
document.writeln("myFish after: " + myFish);
document.writeln("Removed this element: " + shifted);
This example displays the following:

myFish before: ["angel", "clown", "mandarin", "surgeon"]
myFish after: ["clown", "mandarin", "surgeon"]
Removed this element: angel

参看

pop, push, unshift

slice

Extracts a section of an array and returns a new array.

方法源 | Array
实现版本 | Navigator 4.0, Netscape Server 3.0

语法

slice(begin,end)

参数

beginZero-based index at which to begin extraction.
end(Optional) Zero-based index at which to end extraction:
  • slice extracts up to but not including end. slice(1,4) extracts the second element through the fourth element (elements indexed 1, 2, and 3)
  • As a negative index, end indicates an offset from the end of the sequence. slice(2,-1) extracts the third element through the second to last element in the sequence.
  • If end is omitted, slice extracts to the end of the sequence.

描述

slice does not alter the original array, but returns a new "one level deep" copy that contains copies of the elements sliced from the original array. Elements of the original array are copied into the new array as follows:

Object references (and not the actual object) -- slice copies object references into the new array. Both the original and new array refer to the same object. If a referenced object changes, the changes are visible to both the new and original arrays.

Strings and numbers (not String and Number objects)-- slice copies strings and numbers into the new array. Changes to the string or number in one array does not affect the other array.

If a new element is added to either array, the other array is not affected.

示例

In the following example, slice creates a new array, newCar, from myCar. Both include a reference to the object myHonda. When the color of myHonda is changed to purple, both arrays reflect the change.

<SCRIPT LANGUAGE="JavaScript1.2">
//Using slice, create newCar from myCar.
myHonda = {color:"red",wheels:4,engine:{cylinders:4,size:2.2}}
myCar = [myHonda, 2, "cherry condition", "purchased 1997"]
newCar = myCar.slice(0,2)
//Write the values of myCar, newCar, and the color of myHonda
// referenced from both arrays.
document.write("myCar = " + myCar + "<BR>")
document.write("newCar = " + newCar + "<BR>")
document.write("myCar[0].color = " + myCar[0].color + "<BR>")
document.write("newCar[0].color = " + newCar[0].color + "<BR><BR>")
//Change the color of myHonda.
myHonda.color = "purple"
document.write("The new color of my Honda is " + myHonda.color + "<BR><BR>")
//Write the color of myHonda referenced from both arrays.
document.write("myCar[0].color = " + myCar[0].color + "<BR>")
document.write("newCar[0].color = " + newCar[0].color + "<BR>")
</SCRIPT>
This script writes:

myCar = [{color:"red", wheels:4, engine:{cylinders:4, size:2.2}}, 2,
"cherry condition", "purchased 1997"]
newCar = [{color:"red", wheels:4, engine:{cylinders:4, size:2.2}}, 2]
myCar[0].color = red newCar[0].color = red
The new color of my Honda is purple
myCar[0].color = purple
newCar[0].color = purple

splice

Changes the content of an array, adding new elements while removing old elements.

方法源 | Array
实现版本 | Navigator 4.0, Netscape Server 3.0

语法

splice(index, howMany, newElt1, ..., newEltN)

参数

index | Index at which to start changing the array.
howMany | An integer indicating the number of old array elements to remove. If howMany is 0, no elements are removed. In this case, you should specify at least one new element.
newElt1, ..., newEltN | (Optional) The elements to add to the array. If you don't specify any elements, splice simply removes elements from the array.

描述

If you specify a different number of elements to insert than the number you're removing, the array will have a different length at the end of the call.

If howMany is 1, this method returns the single element that it removes. If howMany is more than 1, the method returns an array containing the removed elements.

示例

The following script illustrate the use of splice:

<SCRIPT LANGUAGE="JavaScript1.2">
myFish = ["angel", "clown", "mandarin", "surgeon"];
document.writeln("myFish: " + myFish + "<BR>");
removed = myFish.splice(2, 0, "drum");
document.writeln("After adding 1: " + myFish);
document.writeln("removed is: " + removed + "<BR>");
removed = myFish.splice(3, 1)
document.writeln("After removing 1: " + myFish);
document.writeln("removed is: " + removed + "<BR>");
removed = myFish.splice(2, 1, "trumpet")
document.writeln("After replacing 1: " + myFish);
document.writeln("removed is: " + removed + "<BR>");
removed = myFish.splice(0, 2, "parrot", "anemone", "blue")
document.writeln("After replacing 2: " + myFish);
document.writeln("removed is: " + removed);
</SCRIPT>
This script displays:

myFish: ["angel", "clown", "mandarin", "surgeon"] After adding 1: ["angel", "clown", "drum", "mandarin", "surgeon"]
removed is: undefined After removing 1: ["angel", "clown", "drum", "surgeon"]
removed is: mandarin After replacing 1: ["angel", "clown", "trumpet", "surgeon"]
removed is: drum After replacing 2: ["parrot", "anemone", "blue", "trumpet", "surgeon"]
removed is: ["angel", "clown"]

sort

Sorts the elements of an array.

方法源 | Array
实现版本 | Navigator 3.0, LiveWire 1.0 Navigator 4.0: modified behavior.

语法

sort(compareFunction)

参数

compareFunctionSpecifies a function that defines the sort order. If omitted, the array is sorted lexicographically (in dictionary order) according to the string conversion of each element.

描述

If compareFunction is not supplied, elements are sorted by converting them to strings and comparing strings in lexicographic ("dictionary" or "telephone book," not numerical) order. For example, "80" comes before "9" in lexicographic order, but in a numeric sort 9 comes before 80.

If compareFunction is supplied, the array elements are sorted according to the return value of the compare function. If a and b are two elements being compared, then:

  • If compareFunction(a, b) is less than 0, sort b to a lower index than a.

  • If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements.

  • If compareFunction(a, b) is greater than 0, sort b to a higher index than a.
So, the compare function has the following form:

function compare(a, b) {
if (a is less than b by some ordering criterion)
return -1
if (a is greater than b by the ordering criterion)
return 1
// a must be equal to b
return 0
} To compare numbers instead of strings, the compare function can simply subtract b from a:

function compareNumbers(a, b) {
return a - b
} JavaScript uses a s表 sort: the index partial order of a and b does not change if a and b are equal. If a's index was less than b's before sorting, it will be after sorting, no matter how a and b move due to sorting.

The behavior of the sort method changed between Navigator 3.0 and Navigator 4.0. In Navigator 3.0, on some platforms, the sort method does not work. This method works on all platforms for Navigator 4.0.

In Navigator 4.0, this method no longer converts undefined elements to null; instead it sorts them to the high end of the array. For example, assume you have this script:

<SCRIPT>
a = new Array();
a[0] = "Ant";
a[5] = "Zebra";
function writeArray(x) {
for (i = 0; i < x.length; i++) {
document.write(x[i]);
if (i < x.length-1) document.write(", ");
}
}
writeArray(a);
a.sort();
document.write("<BR><BR>");
writeArray(a);
</SCRIPT>
In Navigator 3.0, JavaScript prints:

ant, null, null, null, null, zebra
ant, null, null, null, null, zebra In Navigator 4.0, JavaScript prints:

ant, undefined, undefined, undefined, undefined, zebra
ant, zebra, undefined, undefined, undefined, undefined

示例

The following example creates four arrays and displays the original array, then the sorted arrays. The numeric arrays are sorted without, then with, a compare function.

<SCRIPT>
stringArray = new Array("Blue","Humpback","Beluga")
numericStringArray = new Array("80","9","700")
numberArray = new Array(40,1,5,200)
mixedNumericArray = new Array("80","9","700",40,1,5,200) function compareNumbers(a, b) {
return a - b
} document.write("<B>stringArray:</B> " + stringArray.join() +"<BR>")
document.write("<B>Sorted:</B> " + stringArray.sort() +"<P>") document.write("<B>numberArray:</B> " + numberArray.join() +"<BR>")
document.write("<B>Sorted without a compare function:</B> " + numberArray.sort() +"<BR>")
document.write("<B>Sorted with compareNumbers:</B> " + numberArray.sort(compareNumbers) +"<P>") document.write("<B>numericStringArray:</B> " + numericStringArray.join() +"<BR>")
document.write("<B>Sorted without a compare function:</B> " + numericStringArray.sort() +"<BR>")
document.write("<B>Sorted with compareNumbers:</B> " + numericStringArray.sort(compareNumbers) +"<P>") document.write("<B>mixedNumericArray:</B> " + mixedNumericArray.join() +"<BR>")
document.write("<B>Sorted without a compare function:</B> " + mixedNumericArray.sort() +"<BR>")
document.write("<B>Sorted with compareNumbers:</B> " + mixedNumericArray.sort(compareNumbers) +"<BR>")
</SCRIPT> This example produces the following output. As the output shows, when a compare function is used, numbers sort correctly whether they are numbers or numeric strings.

stringArray: Blue,Humpback,Beluga
Sorted: Beluga,Blue,Humpback numberArray: 40,1,5,200
Sorted without a compare function: 1,200,40,5
Sorted with compareNumbers: 1,5,40,200 numericStringArray: 80,9,700
Sorted without a compare function: 700,80,9
Sorted with compareNumbers: 9,80,700 mixedNumericArray: 80,9,700,40,1,5,200
Sorted without a compare function: 1,200,40,5,700,80,9
Sorted with compareNumbers: 1,5,9,40,80,200,700

参看

Array.join, Array.reverse

toString

Returns a string representing the specified object.

方法源 | Array
实现版本 | Navigator 3.0, LiveWire 1.0

语法

toString()

参数

 无。

描述

Every object has a toString method that is automatically called when it is to be represented as a text value or when an object is referred to in a string concatenation.

You can use toString within your own code to convert an object into a string, and you can create your own function to be called in place of the default toString method.

For Array objects, the built-in toString method joins the array and returns one string containing each array element separated by commas. For example, the following code creates an array and uses toString to convert the array to a string while writing output.

var monthNames = new Array("Jan","Feb","Mar","Apr")
document.write("monthNames.toString() is " + monthNames.toString()) The output is as follows:

monthNames.toString() is Jan,Feb,Mar,Apr For information on defining your own toString method, see the Object.toString method.

unshift

Adds one or more elements to the beginning of an array and returns the new length of the array.

方法源 | Array
实现版本 | Navigator 4.0, Netscape Server 3.0

语法

arrayName.unshift(elt1,..., eltN)

参数

elt1,...,eltNThe elements to add to the front of the array.

示例

The following code displays the myFish array before and after adding elements to it.

myFish = ["angel", "clown"];
document.writeln("myFish before: " + myFish);
unshifted = myFish.unshift("drum", "lion");
document.writeln("myFish after: " + myFish);
document.writeln("New length: " + unshifted);
This example displays the following:

myFish before: ["angel", "clown"]
myFish after: ["drum", "lion", "angel", "clown"]
New length: 4

参看

pop, push, shift


JavaScript语言参考手册_核心

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

Boolean

 The Boolean object is an object wrapper for a boolean value.

Core object |
实现版本 | Navigator 3.0, LiveWire 1.0

创建源

The Boolean constructor:

new Boolean(value)

参数

value The initial value of the Boolean object. The value is converted to a boolean value, if necessary. If value is omitted or is 0, null, false, or the empty string (""), the object has an initial value of false. All other values, including the string "false", create an object with an initial value of true.

描述

Use a Boolean object when you need to convert a non-boolean value to a boolean value. You can use the Boolean object any place JavaScript expects a primitive boolean value. JavaScript returns the primitive value of the Boolean object by automatically invoking the valueOf method.

属性概览

prototype Defines a 属性 that is shared by all Boolean objects.

方法概览

toString Returns a string representing the specified object.

示例

The following示例 create Boolean objects with an initial value of false:

bNoParam = new Boolean()
bZero = new Boolean(0)
bNull = new Boolean(null)
bEmptyString = new Boolean("")
bfalse = new Boolean(false)
The following示例 create Boolean objects with an initial value of true:

btrue = new Boolean(true)
btrueString = new Boolean("true")
bfalseString = new Boolean("false")
bSuLin = new Boolean("Su Lin")

属性

prototype

 Represents the prototype for this class. You can use the prototype to add properties or methods to all instances of a class. For information on prototypes, see Function.prototype.

属性源 | Boolean
实现版本 | Navigator 3.0, LiveWire 1.0

方法

toString

 Returns a string representing the specified object.

方法源 | Boolean
实现版本 | Navigator 3.0, LiveWire 1.0

语法

toString()

参数

 无。

描述

Every object has a toString method that is automatically called when it is to be represented as a text value or when an object is referred to in a string concatenation.

You can use toString within your own code to convert an object into a string, and you can create your own function to be called in place of the default toString method.

For Boolean objects and values, the built-in toString method returns "true" or "false" depending on the value of the boolean object. In the following code, flag.toString returns "true".

flag = new Boolean(true)
document.write("flag.toString() is " + flag.toString() + "<BR>") For information on defining your own toString method, see the Object.toString method.


JavaScript语言参考手册_核心

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

Date

 Lets you work with dates and times.

Core object
实现版本Navigator 2.0, LiveWire 1.0
Navigator 3.0: 添加了 prototype 属性

创建源

The Date constructor:

new Date()
new Date("month day, year hours:minutes:seconds")
new Date(yr_num, mo_num, day_num)
new Date(yr_num, mo_num, day_num, hr_num, min_num, sec_num)

参数

month, day, year, hours, minutes, seconds | String values representing part of a date.
yr_num, mo_num, day_num, hr_num, min_num, sec_num | Integer values representing part of a date. As an integer value, the month is represented by 0 to 11 with 0=January and 11=December.

描述

If you supply no arguments, the constructor creates a Date object for today's date and time. If you supply some arguments, but not others, the missing arguments are set to 0. If you supply any arguments, you must supply at least the year, month, and day. You can omit the hours, minutes, and seconds.

The way JavaScript handles dates is very similar to the way Java handles dates: both languages have many of the same date methods, and both store dates internally as the number of milliseconds since January 1, 1970 00:00:00. Dates prior to 1970 are not allowed.

属性概览

prototypeAllows the addition of properties to a Date object.

方法概览

getDate | Returns the day of the month for the specified date.
getDay | Returns the day of the week for the specified date.
getHours | Returns the hour in the specified date.
getMinutes | Returns the minutes in the specified date.
getMonth | Returns the month in the specified date.
getSeconds | Returns the seconds in the specified date.
getTime | Returns the numeric value corresponding to the time for the specified date.
getTimezoneOffset | Returns the time-zone offset in minutes for the current locale.
getYear | Returns the year in the specified date.
parse | Returns the number of milliseconds in a date string since January 1, 1970, 00:00:00, local time.
setDate | Sets the day of the month for a specified date.
setHours | Sets the hours for a specified date.
setMinutes | Sets the minutes for a specified date.
setMonth | Sets the month for a specified date.
setSeconds | Sets the seconds for a specified date.
setTime | Sets the value of a Date object.
setYear | Sets the year for a specified date.
toGMTString | Converts a date to a string, using the Internet GMT conventions.
toLocaleString | Converts a date to a string, using the current locale's conventions.
UTC | Returns the number of milliseconds in a Date object since January 1, 1970, 00:00:00, Universal Coordinated Time (GMT).

示例

The following示例 show several ways to assign dates:

today = new Date()
birthday = new Date("December 17, 1995 03:24:00")
birthday = new Date(95,11,17)
birthday = new Date(95,11,17,3,24,0)

属性

prototype

 Represents the prototype for this class. You can use the prototype to add properties or methods to all instances of a class. For information on prototypes, see Function.prototype.

属性源 | Date
实现版本 | Navigator 3.0, LiveWire 1.0

方法

getDate

 Returns the day of the month for the specified date.

方法源 | Date
实现版本 | Navigator 2.0, LiveWire 1.0

语法

getDate()

参数

 无

描述

The value returned by getDate is an integer between 1 and 31.

示例

The second statement below assigns the value 25 to the variable day, based on the value of the Date object Xmas95.

Xmas95 = new Date("December 25, 1995 23:15:00")
day = Xmas95.getDate()

参看

Date.setDate

getDay

Returns the day of the week for the specified date.

方法源 | Date
实现版本 | Navigator 2.0, LiveWire 1.0

语法

getDay()

参数

 无

描述

The value returned by getDay is an integer corresponding to the day of the week: 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on.

示例

The second statement below assigns the value 1 to weekday, based on the value of the Date object Xmas95. December 25, 1995, is a Monday.

Xmas95 = new Date("December 25, 1995 23:15:00")
weekday = Xmas95.getDay()

getHours

Returns the hour for the specified date.

方法源 | Date
实现版本 | Navigator 2.0, LiveWire 1.0

语法

getHours()

参数

 无

描述

The value returned by getHours is an integer between 0 and 23.

示例

The second statement below assigns the value 23 to the variable hours, based on the value of the Date object Xmas95.

Xmas95 = new Date("December 25, 1995 23:15:00")
hours = Xmas95.getHours()

参看

Date.setHours

getMinutes

Returns the minutes in the specified date.

方法源 | Date
实现版本 | Navigator 2.0, LiveWire 1.0

语法

getMinutes()

参数

 无

描述

The value returned by getMinutes is an integer between 0 and 59.

示例

The second statement below assigns the value 15 to the variable minutes, based on the value of the Date object Xmas95.

Xmas95 = new Date("December 25, 1995 23:15:00")
minutes = Xmas95.getMinutes()

参看

Date.setMinutes

getMonth

Returns the month in the specified date.

方法源 | Date
实现版本 | Navigator 2.0, LiveWire 1.0

语法

getMonth()

参数

 无

描述

The value returned by getMonth is an integer between 0 and 11. 0 corresponds to January, 1 to February, and so on.

示例

The second statement below assigns the value 11 to the variable month, based on the value of the Date object Xmas95.

Xmas95 = new Date("December 25, 1995 23:15:00")
month = Xmas95.getMonth()

参看

Date.setMonth

getSeconds

Returns the seconds in the current time.

方法源 | Date
实现版本 | Navigator 2.0, LiveWire 1.0

语法

getSeconds()

参数

 无

描述

The value returned by getSeconds is an integer between 0 and 59.

示例

The second statement below assigns the value 30 to the variable secs, based on the value of the Date object Xmas95.

Xmas95 = new Date("December 25, 1995 23:15:30")
secs = Xmas95.getSeconds()

参看

Date.setSeconds

getTime

Returns the numeric value corresponding to the time for the specified date.

方法源 | Date
实现版本 | Navigator 2.0, LiveWire 1.0

语法

getTime()

参数

 无

描述

The value returned by the getTime method is the number of milliseconds since 1 January 1970 00:00:00. You can use this method to help assign a date and time to another Date object.

示例

The following example assigns the date value of theBigDay to sameAsBigDay:

theBigDay = new Date("July 1, 1999")
sameAsBigDay = new Date()
sameAsBigDay.setTime(theBigDay.getTime())

参看

Date.setTime

getTimezoneOffset

Returns the time-zone offset in minutes for the current locale.

方法源 | Date
实现版本 | Navigator 2.0, LiveWire 1.0

语法

getTimezoneOffset()

参数

 无

描述

The time-zone offset is the difference between local time and Greenwich Mean Time (GMT). Daylight savings time prevents this value from being a constant.

示例

x = new Date()
currentTimeZoneOffsetInHours = x.getTimezoneOffset()/60

getYear

 Returns the year in the specified date.

方法源 | Date
实现版本 | Navigator 2.0, LiveWire 1.0

语法

getYear()

参数

 无

描述

The getYear method returns either a 2-digit or 4-digit year:

  • For years between and including 1900 and 1999, the value returned by getYear is the year minus 1900. For example, if the year is 1976, the value returned is 76.

  • For years less than 1900 or greater than 1999, the value returned by getYear is the four-digit year. For example, if the year is 1856, the value returned is 1856. If the year is 2026, the value returned is 2026.

示例

 示例 1. The second statement assigns the value 95 to the variable year.

Xmas = new Date("December 25, 1995 23:15:00")
year = Xmas.getYear() 示例 2. The second statement assigns the value 2000 to the variable year.

Xmas = new Date("December 25, 2000 23:15:00")
year = Xmas.getYear() 示例 3. The second statement assigns the value 95 to the variable year, representing the year 1995.

Xmas.setYear(95)
year = Xmas.getYear()

参看

Date.setYear

parse

Returns the number of milliseconds in a date string since January 1, 1970, 00:00:00, local time.

方法源 | Date
静态
实现版本 | Navigator 2.0, LiveWire 1.0

语法

Date.parse(dateString)

参数

 :

dateStringA string representing a date.

描述

The parse method takes a date string (such as "Dec 25, 1995") and returns the number of milliseconds since January 1, 1970, 00:00:00 (local time). This function is useful for setting date values based on string values, for example in conjunction with the setTime method and the Date object.

Given a string representing a time, parse returns the time value. It accepts the IETF standard date语法: "Mon, 25 Dec 1995 13:30:00 GMT". It understands the continental US time-zone abbreviations, but for general use, use a time-zone offset, for example, "Mon, 25 Dec 1995 13:30:00 GMT+0430" (4 hours, 30 minutes west of the Greenwich meridian). If you do not specify a time zone, the local time zone is assumed. GMT and UTC are considered equivalent.

Because parse is a static method of Date, you always use it as Date.parse(), rather than as a method of a Date object you created.

示例

If IPOdate is an existing Date object, then you can set it to August 9, 1995 as follows:

IPOdate.setTime(Date.parse("Aug 9, 1995"))

参看

Date.UTC

setDate

Sets the day of the month for a specified date.

方法源 | Date
实现版本 | Navigator 2.0, LiveWire 1.0

语法

setDate(dayValue)

参数

dayValueAn integer from 1 to 31, representing the day of the month.

示例

The second statement below changes the day for theBigDay to July 24 from its original value.

theBigDay = new Date("July 27, 1962 23:30:00")
theBigDay.setDate(24)

参看

Date.getDate

setHours

Sets the hours for a specified date.

方法源 | Date
实现版本 | Navigator 2.0, LiveWire 1.0

语法

setHours(hoursValue)

参数

hoursValueAn integer between 0 and 23, representing the hour.

示例

theBigDay.setHours(7)

参看

 Date.getHours

setMinutes

Sets the minutes for a specified date.

方法源 | Date
实现版本 | Navigator 2.0, LiveWire 1.0

语法

setMinutes(minutesValue)

参数

minutesValueAn integer between 0 and 59, representing the minutes.

示例

theBigDay.setMinutes(45)

参看

 Date.getMinutes

setMonth

Sets the month for a specified date.

方法源 | Date
实现版本 | Navigator 2.0, LiveWire 1.0

语法

setMonth(monthValue)

参数

monthValueAn integer between 0 and 11 (representing the months January through December).

示例

theBigDay.setMonth(6)

参看

 Date.getMonth

setSeconds

Sets the seconds for a specified date.

方法源 | Date
实现版本 | Navigator 2.0, LiveWire 1.0

语法

setSeconds(secondsValue)

参数

secondsValueAn integer between 0 and 59.

示例

theBigDay.setSeconds(30)

参看

 Date.getSeconds

setTime

Sets the value of a Date object.

方法源 | Date
实现版本 | Navigator 2.0, LiveWire 1.0

语法

setTime(timevalue)

参数

timevalueAn integer representing the number of milliseconds since 1 January 1970 00:00:00.

描述

Use the setTime method to help assign a date and time to another Date object.

示例

theBigDay = new Date("July 1, 1999")
sameAsBigDay = new Date()
sameAsBigDay.setTime(theBigDay.getTime())

参看

 Date.getTime

setYear

Sets the year for a specified date.

方法源 | Date
实现版本 | Navigator 2.0, LiveWire 1.0

语法

setYear(yearValue)

参数

yearValueAn integer.

描述

If yearValue is a number between 0 and 99 (inclusive), then the year for dateObjectName is set to 1900 + yearValue. Otherwise, the year for dateObjectName is set to yearValue.

示例

Note that there are two ways to set years in the 20th century.

示例 1. The year is set to 1996.

theBigDay.setYear(96) 示例 2. The year is set to 1996.

theBigDay.setYear(1996) 示例 3. The year is set to 2000.

theBigDay.setYear(2000)

参看

Date.getYear

toGMTString

Converts a date to a string, using the Internet GMT conventions.

方法源 | Date
实现版本 | Navigator 2.0, LiveWire 1.0

语法

toGMTString()

参数

 无

描述

The exact format of the value returned by toGMTString varies according to the platform.

示例

In the following example, today is a Date object:

today.toGMTString() In this example, the toGMTString method converts the date to GMT (UTC) using the operating system's time-zone offset and returns a string value that is similar to the following form. The exact format depends on the platform.

Mon, 18 Dec 1995 17:28:35 GMT

参看

Date.toLocaleString

toLocaleString

Converts a date to a string, using the current locale's conventions.

方法源 | Date
实现版本 | Navigator 2.0, LiveWire 1.0

语法

toLocaleString()

参数

 无

描述

If you pass a date using toLocaleString, be aware that different platforms assemble the string in different ways. Using methods such as getHours, getMinutes, and getSeconds gives more por表 results.

示例

In the following example, today is a Date object:

today = new Date(95,11,18,17,28,35) //months are represented by 0 to 11
today.toLocaleString() In this example, toLocaleString returns a string value that is similar to the following form. The exact format depends on the platform.

12/18/95 17:28:35

参看

Date.toGMTString

UTC

Returns the number of milliseconds in a Date object since January 1, 1970, 00:00:00, Universal Coordinated Time (GMT).

方法源 | Date
静态
实现版本 | Navigator 2.0, LiveWire 1.0

语法

Date.UTC(year, month, day, hrs, min, sec)

参数

year | A year after 1900.
month | A month between 0 and 11.
date | A day of the month between 1 and 31.
hrs | (Optional) A number of hours between 0 and 23.
min | (Optional) A number of minutes between 0 and 59.
sec | (Optional) A number of seconds between 0 and 59.

描述

UTC takes comma-delimited date parameters and returns the number of milliseconds since January 1, 1970, 00:00:00, Universal Coordinated Time (GMT).

Because UTC is a static method of Date, you always use it as Date.UTC(), rather than as a method of a Date object you created.

示例

The following statement creates a Date object using GMT instead of local time:

gmtDate = new Date(Date.UTC(96, 11, 1, 0, 0, 0))

参看

Date.parse


JavaScript语言参考手册_核心

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

Function

 Specifies a string of JavaScript code to be compiled as a function.

Core object
实现版本Navigator 3.0, LiveWire 1.0
Navigator 4.0: 添加了 arity 属性.

创建源

The Function constructor:

new Function (arg1, arg2, ... argN, functionBody)

参数

arg1, arg2, ... argN | (Optional) Names to be used by the function as formal argument names. Each must be a string that corresponds to a valid JavaScript identifier; for example "x" or "theForm".
functionBody | A string containing the JavaScript statements comprising the function definition.

描述

Function objects are evaluated each time they are used. This is less efficient than declaring a function and calling it within your code, because declared functions are compiled.

In addition to defining functions as described here, you can also use the function statement, as described in the JavaScript Guide.

属性概览

arguments | An array corresponding to the arguments passed to a function.
arity | Indicates the number of arguments expected by the function.
caller | Specifies which function called the current function.
prototype | Allows the addition of properties to a Function object.

方法概览

toStringReturns a string representing the specified object.

Specifying a variable value with a Function object

The following code assigns a function to the variable setBGColor. This function sets the current document's background color.

var setBGColor = new Function("document.bgColor='antiquewhite'") To call the Function object, you can specify the variable name as if it were a function. The following code executes the function specified by the setBGColor variable:

var colorChoice="antiquewhite"
if (colorChoice=="antiquewhite") {setBGColor()} You can assign the function to an event handler in either of the following ways:

document.form1.colorButton.onclick=setBGColor
<INPUT NAME="colorButton" TYPE="button"
VALUE="Change background color"
onClick="setBGColor()">
Creating the variable setBGColor shown above is similar to declaring the following function:

function setBGColor() {
document.bgColor='antiquewhite'
}
Assigning a function to a variable is similar to declaring a function, but they have differences:

  • When you assign a function to a variable using var setBGColor = new Function("..."), setBGColor is a variable for which the current value is a reference to the function created with new Function().

  • When you create a function using function setBGColor() {...}, setBGColor is not a variable, it is the name of a function.

Specifying参数in a Function object

 The following code specifies a Function object that takes two arguments.

var multFun = new Function("x", "y", "return x * y") The string arguments "x" and "y" are formal argument names that are used in the function body, "return x * y".

The following code shows several ways to call the function multFun:

var theAnswer = multFun(7,6)
document.write("15*2 = " + multFun(15,2))
<INPUT NAME="operand1" TYPE="text" VALUE="5" SIZE=5>
<INPUT NAME="operand2" TYPE="text" VALUE="6" SIZE=5>
<INPUT NAME="result" TYPE="text" VALUE="" SIZE=10>
<INPUT NAME="buttonM" TYPE="button" VALUE="Multiply"
onClick="document.form1.result.value=
multFun(document.form1.operand1.value,
document.form1.operand2.value)">
You cannot call the function multFun in an object's event handler property, because event handler properties cannot take arguments. For example, you cannot call the function multFun by setting a button's onclick property as follows:

document.form1.button1.onclick=multFun(5,10)

Specifying an event handler with a Function object

The following code assigns a function to a window's onFocus event handler (the event handler must be spelled in all lowercase):

window.onfocus = new Function("document.bgColor='antiquewhite'") Once you have a reference to a function object, you can use it like a function and it will convert from an object to a function:

window.onfocus() Event handlers do not take arguments, so you cannot declare any arguments in the Function constructor for an event handler.

示例

示例 1. The following example creates onFocus and onBlur event handlers for a frame. This code exists in the same file that contains the FRAMESET tag. Note that this is the only way to create onFocus and onBlur event handlers for a frame, because you cannot specify the event handlers in the FRAME tag.

frames[0].onfocus = new Function("document.bgColor='antiquewhite'")
frames[0].onblur = new Function("document.bgColor='lightgrey'") 示例 2. You can determine whether a function exists by comparing the function name to null. In the following example, func1 is called if the function noFunc does not exist; otherwise func2 is called. Notice that the window name is needed when referring to the function name noFunc.

if (window.noFunc == null)
func1()
else func2()

属性

arguments

 An array corresponding to the arguments passed to a function.

属性源 | Function
实现版本 | Navigator 3.0, LiveWire 1.0 Navigator 4.0

描述

You can call a function with more arguments than it is formally declared to accept by using the arguments array. This technique is useful if a function can be passed a variable number of arguments. You can use arguments.length to determine the number of arguments passed to the function, and then treat each argument by using the arguments array.

The arguments array is available only within a function declaration. Attempting to access the arguments array outside a function declaration results in an error.

The this keyword does not refer to the currently executing function, so you must refer to functions and Function objects by name, even within the function body. In JavaScript 1.2, arguments includes these additional properties:

  • formal arguments--each formal argument of a function is a property of the arguments array.

  • local variables--each local variable of a function is a property of the arguments array.

  • caller--a property whose value is the arguments array of the outer function. If there is no outer function, the value is undefined.

  • callee--a property whose value is the function reference.
For example, the following script demonstrates several of the arguments properties:

<SCRIPT> function b(z) {
document.write(arguments.z + "<BR>")
document.write (arguments.caller.x + "<BR>")
return 99
} function a(x, y) {
return b(534)
} document.write (a(2,3) + "<BR>") </SCRIPT> This displays:

534
2
99

534 is the actual parameter to b, so it is the value of arguments.z.

2 is a's actual x parameter, so (viewed within b) it is the value of arguments.caller.x.

99 is what a(2,3) returns.

示例

This example defines a function that creates HTML lists. The only formal argument for the function is a string that is "U" if the list is to be unordered (bulleted), or "O" if the list is to be ordered (numbered). The function is defined as follows:

function list(type) {
document.write("<" + type + "L>")
for (var i=1; i<list.arguments.length; i++) {
document.write("<LI>" + list.arguments[i])
document.write("</" + type + "L>")
}
}
You can pass any number of arguments to this function, and it displays each argument as an item in the type of list indicated. For example, the following call to the function

list("U", "One", "Two", "Three") results in this output:

<UL>
<LI>One
<LI>Two
<LI>Three
</UL> In server-side JavaScript, you can display the same output by calling the write function instead of using document.write.

arity

When the LANGUAGE attribute of the SCRIPT tag is "JavaScript1.2", this property indicates the number of arguments expected by a function.

属性源 | Function
实现版本 | Navigator 4.0, Netscape Server 3.0

描述

arity is external to the function, and indicates how many arguments the function expects. By contrast, arguments.length provides the number of arguments actually passed to the function.

示例

The following example demonstrates the use of arity and arguments.length.

<SCRIPT LANGUAGE = "JavaScript1.2">
function addNumbers(x,y){
document.write("length = " + arguments.length + "<BR>")
z = x + y
}
document.write("arity = " + addNumbers.arity + "<BR>")
addNumbers(3,4,5)
</SCRIPT>
This script writes:

arity = 2
length = 3

caller

Returns the name of the function that invoked the currently executing function.

属性源 | Function
实现版本 | Navigator 3.0, LiveWire 1.0

描述

The caller property is available only within the body of a function. If used outside a function declaration, the caller property is null.

If the currently executing function was invoked by the top level of a JavaScript program, the value of caller is null.

The this keyword does not refer to the currently executing function, so you must refer to functions and Function objects by name, even within the function body.

The caller property is a reference to the calling function, so

  • If you use it in a string context, you get the result of calling functionName.toString. That is, the decompiled canonical source form of the function.

  • You can also call the calling function, if you know what arguments it might want. Thus, a called function can call its caller without knowing the name of the particular caller, provided it knows that all of its callers have the same form and fit, and that they will not call the called function again unconditionally (which would result in infinite recursion).

示例

 The following code checks the value of a function's caller property.

function myFunc() {
if (myFunc.caller == null) {
alert("The function was called from the top!")
} else alert("This function's caller was " + myFunc.caller)
}

参看

Function.arguments

prototype

A value from which instances of a particular class are created. Every object that can be created by calling a constructor function has an associated prototype property.

属性源 | Object
实现版本 | Navigator 3.0, LiveWire 1.0

描述

You can add new properties or methods to an existing class by adding them to the prototype associated with the constructor function for that class. The语法 for adding a new property or method is:

fun.prototype.name = value where

fun | The name of the constructor function object you want to change.
name | The name of the 属性 or 方法 to be created.
value | The value initially assigned to the new 属性 or 方法。

If you add a new property to the prototype for an object, then all objects created with that object's constructor function will have that new property, even if the objects existed before you created the new property. For example, assume you have the following statements:

var array1 = new Array();
var array2 = new Array(3);
Array.prototype.description=null;
array1.description="Contains some stuff"
array2.description="Contains other stuff"
After you set a property for the prototype, all subsequent objects created with Array will have the property:

anotherArray=new Array()
anotherArray.description="Currently empty"

示例

The following example creates a method, str_rep, and uses the statement String.prototype.rep = str_rep to add the method to all String objects. All objects created with new String() then have that method, even objects already created. The example then creates an alternate method and adds that to one of the String objects using the statement s1.rep = fake_rep. The str_rep method of the remaining String objects is not altered.

var s1 = new String("a")
var s2 = new String("b")
var s3 = new String("c")
// Create a repeat-string-N-times method for all String objects
function str_rep(n) {
var s = "", t = this.toString()
while (--n >= 0) s += t
return s
}
String.prototype.rep = str_rep
// Display the results
document.write("<P>s1.rep(3) is " + s1.rep(3)) // "aaa"
document.write("<BR>s2.rep(5) is " + s2.rep(5)) // "bbbbb"
document.write("<BR>s3.rep(2) is " + s3.rep(2)) // "cc"
// Create an alternate method and assign it to only one String variable
function fake_rep(n) {
return "repeat " + this + n + " times."
}
s1.rep = fake_rep
document.write("<P>s1.rep(1) is " + s1.rep(1)) // "repeat a 1 times."
document.write("<BR>s2.rep(4) is " + s2.rep(4)) // "bbbb"
document.write("<BR>s3.rep(6) is " + s3.rep(6)) // "cccccc"
This example produces the following output:

s1.rep(3) is aaa
s2.rep(5) is bbbbb
s3.rep(2) is cc
s1.rep(1) is repeat a1 times.
s2.rep(4) is bbbb
s3.rep(6) is cccccc
The function in this example also works on String objects not created with the String constructor. The following code returns "zzz".

"z".rep(3)

方法

toString

 Returns a string representing the specified object.

方法源 | Function
实现版本 | Navigator 3.0, LiveWire 1.0

语法

toString()

参数

 无。

描述

Every object has a toString method that is automatically called when it is to be represented as a text value or when an object is referred to in a string concatenation.

You can use toString within your own code to convert an object into a string, and you can create your own function to be called in place of the default toString method.

For Function objects, the built-in toString method decompiles the function back into the JavaScript source that defines the function. This string includes the function keyword, the argument list, curly braces, and function body.

For example, assume you have the following code that defines the Dog object type and creates theDog, an object of type Dog:

function Dog(name,breed,color,sex) {
this.name=name
this.breed=breed
this.color=color
this.sex=sex
}
theDog = new Dog("Gabby","Lab","chocolate","girl")
Any time Dog is used in a string context, JavaScript automatically calls the toString function, which returns the following string:

function Dog(name, breed, color, sex) { this.name = name; this.breed = breed; this.color = color; this.sex = sex; }
For information on defining your own toString method, see the Object.toString method.


JavaScript语言参考手册_核心

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

Math

 A built-in object that has properties and methods for mathematical constants and functions. For example, the Math object's PI property has the value of pi.

Core object.
实现版本Navigator 2.0, LiveWire 1.0

创建源

The Math object is a top-level, predefined JavaScript object. You can automatically access it without using a constructor or calling a method.

描述

All properties and methods of Math are static. You refer to the constant PI as Math.PI and you call the sine function as Math.sin(x), where x is the method's argument. Constants are defined with the full precision of real numbers in JavaScript.

It is often convenient to use the with statement when a section of code uses several Math constants and methods, so you don't have to type "Math" repeatedly. For example,

with (Math) {
a = PI * r*r
y = r*sin(theta)
x = r*cos(theta)
}

属性概览

E | Euler's constant and the base of natural logarithms, approximately 2.718.
LN10 | Natural logarithm of 10, approximately 2.302.
LN2 | Natural logarithm of 2, approximately 0.693.
LOG10E | Base 10 logarithm of E (approximately 0.434).
LOG2E | Base 2 logarithm of E (approximately 1.442).
PI | Ratio of the circumference of a circle to its diameter, approximately 3.14159.
SQRT1_2 | Square root of 1/2; equivalently, 1 over the square root of 2, approximately 0.707.
SQRT2 | Square root of 2, approximately 1.414.

方法概览

abs | Returns the absolute value of a number.
acos | Returns the arccosine (in radians) of a number.
asin | Returns the arcsine (in radians) of a number.
atan | Returns the arctangent (in radians) of a number.
atan2 | Returns the arctangent of the quotient of its arguments.
ceil | Returns the smallest integer greater than or equal to a number.
cos | Returns the cosine of a number.
exp | Returns Enumber, where number is the argument, and E is Euler's constant, the base of the natural logarithms.
floor | Returns the largest integer less than or equal to a number.
log | Returns the natural logarithm (base E) of a number.
max | Returns the greater of two numbers.
min | Returns the lesser of two numbers.
pow | Returns base to the exponent power, that is, baseexponent.
random | Returns a pseudo-random number between 0 and 1.
round | Returns the value of a number rounded to the nearest integer.
sin | Returns the sine of a number.
sqrt | Returns the square root of a number.
tan | Returns the tangent of a number.

属性

E

 Euler's constant and the base of natural logarithms, approximately 2.718.

属性源 | Math
静态, 只读
实现版本 | Navigator 2.0, LiveWire 1.0

示例

The following function returns Euler's constant:

function getEuler() {
return Math.E
}

描述

Because E is a static property of Math, you always use it as Math.E, rather than as a property of a Math object you created.

LN10

The natural logarithm of 10, approximately 2.302.

属性源 | Math
静态, 只读
实现版本 | Navigator 2.0, LiveWire 1.0

示例

The following function returns the natural log of 10:

function getNatLog10() {
return Math.LN10
}

描述

Because LN10 is a static property of Math, you always use it as Math.LN10, rather than as a property of a Math object you created.

LN2

The natural logarithm of 2, approximately 0.693.

属性源 | Math
静态, 只读
实现版本 | Navigator 2.0, LiveWire 1.0

示例

The following function returns the natural log of 2:

function getNatLog2() {
return Math.LN2
}

描述

Because LN2 is a static property of Math, you always use it as Math.LN2, rather than as a property of a Math object you created.

LOG10E

The base 10 logarithm of E (approximately 0.434).

属性源 | Math
静态, 只读
实现版本 | Navigator 2.0, LiveWire 1.0

示例

The following function returns the base 10 logarithm of E:

function getLog10e() {
return Math.LOG10E
}

描述

Because LOG10E is a static property of Math, you always use it as Math.LOG10E, rather than as a property of a Math object you created.

LOG2E

The base 2 logarithm of E (approximately 1.442).

属性源 | Math
静态, 只读
实现版本 | Navigator 2.0, LiveWire 1.0

示例

The following function returns the base 2 logarithm of E:

function getLog2e() {
return Math.LOG2E
}

描述

Because LOG2E is a static property of Math, you always use it as Math.LOG2E, rather than as a property of a Math object you created.

PI

The ratio of the circumference of a circle to its diameter, approximately 3.14159.

属性源 | Math
静态, 只读
实现版本 | Navigator 2.0, LiveWire 1.0

示例

The following function returns the value of pi:

function getPi() {
return Math.PI
}

描述

Because PI is a static property of Math, you always use it as Math.PI, rather than as a property of a Math object you created.

SQRT1_2

The square root of 1/2; equivalently, 1 over the square root of 2, approximately 0.707.

属性源 | Math
静态, 只读
实现版本 | Navigator 2.0, LiveWire 1.0

示例

The following function returns 1 over the square root of 2:

function getRoot1_2() {
return Math.SQRT1_2
}

描述

Because SQRT1_2 is a static property of Math, you always use it as Math.SQRT1_2, rather than as a property of a Math object you created.

SQRT2

The square root of 2, approximately 1.414.

属性源 | Math
静态, 只读
实现版本 | Navigator 2.0, LiveWire 1.0

示例

The following function returns the square root of 2:

function getRoot2() {
return Math.SQRT2
}

描述

Because SQRT2 is a static property of Math, you always use it as Math.SQRT2, rather than as a property of a Math object you created.

方法

abs

 Returns the absolute value of a number.

方法源 | Math
静态
实现版本 | Navigator 2.0, LiveWire 1.0

语法

abs(x)

参数

xA number

示例

The following function returns the absolute value of the variable x:

function getAbs(x) {
return Math.abs(x)
}

描述

Because abs is a static method of Math, you always use it as Math.abs(), rather than as a method of a Math object you created.

acos

Returns the arccosine (in radians) of a number.

方法源 | Math
静态
实现版本 | Navigator 2.0, LiveWire 1.0

语法

acos(x)

参数

xA number

描述

The acos method returns a numeric value between 0 and pi radians. If the value of number is outside this range, it returns 0.

Because acos is a static method of Math, you always use it as Math.acos(), rather than as a method of a Math object you created.

示例

The following function returns the arccosine of the variable x:

function getAcos(x) {
return Math.acos(x)
}
If you pass -1 to getAcos, it returns 3.141592653589793; if you pass 2, it returns 0 because 2 is out of range.

参看

Math.asin, Math.atan, Math.atan2, Math.cos, Math.sin, Math.tan

asin

Returns the arcsine (in radians) of a number.

方法源 | Math
静态
实现版本 | Navigator 2.0, LiveWire 1.0

语法

asin(x)

参数

xA number

描述

The asin method returns a numeric value between -pi/2 and pi/2 radians. If the value of number is outside this range, it returns 0.

Because asin is a static method of Math, you always use it as Math.asin(), rather than as a method of a Math object you created.

示例

The following function returns the arcsine of the variable x:

function getAsin(x) {
return Math.asin(x)
}
If you pass getAsin the value 1, it returns 1.570796326794897 (pi/2); if you pass it the value 2, it returns 0 because 2 is out of range.

参看

Math.acos, Math.atan, Math.atan2, Math.cos, Math.sin, Math.tan

atan

Returns the arctangent (in radians) of a number.

方法源 | Math
静态
实现版本 | Navigator 2.0, LiveWire 1.0

语法

atan(x)

参数

xA number

描述

The atan method returns a numeric value between -pi/2 and pi/2 radians.

Because atan is a static method of Math, you always use it as Math.atan(), rather than as a method of a Math object you created.

示例

The following function returns the arctangent of the variable x:

function getAtan(x) {
return Math.atan(x)
}
If you pass getAtan the value 1, it returns 0.7853981633974483; if you pass it the value .5, it returns 0.4636476090008061.

参看

Math.acos, Math.asin, Math.atan2, Math.cos, Math.sin, Math.tan

atan2

Returns the arctangent of the quotient of its arguments.

方法源 | Math
静态
实现版本 | Navigator 2.0, LiveWire 1.0

语法

atan2(y, x)

参数

y, xNumber

描述

The atan2 method returns a numeric value between -pi and pi representing the angle theta of an (x,y) point. This is the counterclockwise angle, measured in radians, between the positive X axis, and the point (x,y). Note that the arguments to this function pass the y-coordinate first and the x-coordinate second.

atan2 is passed separate x and y arguments, and atan is passed the ratio of those two arguments.

Because atan2 is a static method of Math, you always use it as Math.atan2(), rather than as a method of a Math object you created.

示例

The following function returns the angle of the polar coordinate:

function getAtan2(x,y) {
return Math.atan2(x,y)
}
If you pass getAtan2 the values (90,15), it returns 1.4056476493802699; if you pass it the values (15,90), it returns 0.16514867741462683.

参看

Math.acos, Math.asin, Math.atan, Math.cos, Math.sin, Math.tan

ceil

Returns the smallest integer greater than or equal to a number.

方法源 | Math
静态
实现版本 | Navigator 2.0, LiveWire 1.0

语法

ceil(x)

参数

xA number

描述

Because ceil is a static method of Math, you always use it as Math.ceil(), rather than as a method of a Math object you created.

示例

The following function returns the ceil value of the variable x:

function getCeil(x) {
return Math.ceil(x)
}
If you pass 45.95 to getCeil, it returns 46; if you pass -45.95, it returns -45.

参看

Math.floor

cos

Returns the cosine of a number.

方法源 | Math
静态
实现版本 | Navigator 2.0, LiveWire 1.0

语法

cos(x)

参数

xA number

描述

The cos method returns a numeric value between -1 and 1, which represents the cosine of the angle.

Because cos is a static method of Math, you always use it as Math.cos(), rather than as a method of a Math object you created.

示例

The following function returns the cosine of the variable x:

function getCos(x) {
return Math.cos(x)
}
If x equals Math.PI/2, getCos returns 6.123031769111886e-017; if x equals Math.PI, getCos returns -1.

参看

Math.acos, Math.asin, Math.atan, Math.atan2, Math.sin, Math.tan

exp

Returns Ex, where x is the argument, and E is Euler's constant, the base of the natural logarithms.

方法源 | Math
静态
实现版本 | Navigator 2.0, LiveWire 1.0

语法

exp(x)

参数

xA number

描述

Because exp is a static method of Math, you always use it as Math.exp(), rather than as a method of a Math object you created.

示例

The following function returns the exponential value of the variable x:

function getExp(x) {
return Math.exp(x)
}
If you pass getExp the value 1, it returns 2.718281828459045.

参看

Math.E, Math.log, Math.pow

floor

Returns the largest integer less than or equal to a number.

方法源 | Math
静态
实现版本 | Navigator 2.0, LiveWire 1.0

语法

floor(x)

参数

xA number

描述

Because floor is a static method of Math, you always use it as Math.floor(), rather than as a method of a Math object you created.

示例

The following function returns the floor value of the variable x:

function getFloor(x) {
return Math.floor(x)
}
If you pass 45.95 to getFloor, it returns 45; if you pass -45.95, it returns -46.

参看

Math.ceil

log

Returns the natural logarithm (base E) of a number.

方法源 | Math
静态
实现版本 | Navigator 2.0, LiveWire 1.0

语法

log(x)

参数

xA number

描述

If the value of number is outside the suggested range, the return value is always -1.797693134862316e+308.

Because log is a static method of Math, you always use it as Math.log(), rather than as a method of a Math object you created.

示例

The following function returns the natural log of the variable x:

function getLog(x) {
return Math.log(x)
}
If you pass getLog the value 10, it returns 2.302585092994046; if you pass it the value 0, it returns -1.797693134862316e+308 because 0 is out of range.

参看

Math.exp, Math.pow

max

Returns the larger of two numbers.

方法源 | Math
静态
实现版本 | Navigator 2.0, LiveWire 1.0

语法

max(x,y)

参数

x, yNumbers.

描述

Because max is a static method of Math, you always use it as Math.max(), rather than as a method of a Math object you created.

示例

The following function evaluates the variables x and y:

function getMax(x,y) {
return Math.max(x,y)
}
If you pass getMax the values 10 and 20, it returns 20; if you pass it the values -10 and -20, it returns -10.

参看

Math.min

min

Returns the smaller of two numbers.

方法源 | Math
静态
实现版本 | Navigator 2.0, LiveWire 1.0

语法

min(x,y)

参数

x, yNumbers.

描述

Because min is a static method of Math, you always use it as Math.min(), rather than as a method of a Math object you created.

示例

The following function evaluates the variables x and y:

function getMin(x,y) {
return Math.min(x,y)
}
If you pass getMin the values 10 and 20, it returns 10; if you pass it the values -10 and -20, it returns -20.

参看

Math.max

pow

Returns base to the exponent power, that is, baseexponent.

方法源 | Math
静态
实现版本 | Navigator 2.0, LiveWire 1.0

语法

pow(x,y)

参数

base | The base number
exponent | The exponent to which to raise base

描述

Because pow is a static method of Math, you always use it as Math.pow(), rather than as a method of a Math object you created.

示例

function raisePower(x,y) {
return Math.pow(x,y)
} If x is 7 and y is 2, raisePower returns 49 (7 to the power of 2).

参看

Math.exp, Math.log

random

Returns a pseudo-random number between 0 and 1. The random number generator is seeded from the current time, as in Java.

方法源 | Math
静态
实现版本 | Navigator 2.0, LiveWire 1.0: Unix only Navigator 3.0, LiveWire 1.0: all platforms

语法

random()

参数

 无。

描述

Because random is a static method of Math, you always use it as Math.random(), rather than as a method of a Math object you created.

示例

//Returns a random number between 0 and 1
function getRandom() {
return Math.random()
}

round

 Returns the value of a number rounded to the nearest integer.

方法源 | Math
静态
实现版本 | Navigator 2.0, LiveWire 1.0

语法

round(x)

参数

xA number

描述

If the fractional portion of number is .5 or greater, the argument is rounded to the next highest integer. If the fractional portion of number is less than .5, the argument is rounded to the next lowest integer.

Because round is a static method of Math, you always use it as Math.round(), rather than as a method of a Math object you created.

示例

//Displays the value 20
document.write("The rounded value is " + Math.round(20.49)) //Displays the value 21
document.write("<P>The rounded value is " + Math.round(20.5)) //Displays the value -20
document.write("<P>The rounded value is " + Math.round(-20.5)) //Displays the value -21
document.write("<P>The rounded value is " + Math.round(-20.51)) In server-side JavaScript, you can display the same output by calling the write function instead of using document.write.

sin

Returns the sine of a number.

方法源 | Math
静态
实现版本 | Navigator 2.0, LiveWire 1.0

语法

sin(x)

参数

xA number

描述

The sin method returns a numeric value between -1 and 1, which represents the sine of the argument.

Because sin is a static method of Math, you always use it as Math.sin(), rather than as a method of a Math object you created.

示例

The following function returns the sine of the variable x:

function getSine(x) {
return Math.sin(x)
}
If you pass getSine the value Math.PI/2, it returns 1.

参看

Math.acos, Math.asin, Math.atan, Math.atan2, Math.cos, Math.tan

sqrt

Returns the square root of a number.

方法源 | Math
静态
实现版本 | Navigator 2.0, LiveWire 1.0

语法

sqrt(x)

参数

xA number

描述

If the value of number is outside the required range, sqrt returns 0.

Because sqrt is a static method of Math, you always use it as Math.sqrt(), rather than as a method of a Math object you created.

示例

The following function returns the square root of the variable x:

function getRoot(x) {
return Math.sqrt(x)
}
If you pass getRoot the value 9, it returns 3; if you pass it the value 2, it returns 1.414213562373095.

tan

Returns the tangent of a number.

方法源 | Math
静态
实现版本 | Navigator 2.0, LiveWire 1.0

语法

tan(x)

参数

xA number

描述

The tan method returns a numeric value that represents the tangent of the angle.

Because tan is a static method of Math, you always use it as Math.tan(), rather than as a method of a Math object you created.

示例

The following function returns the tangent of the variable x:

function getTan(x) {
return Math.tan(x)
}
If you pass Math.PI/4 to getTan, it returns 0.9999999999999999.

参看

Math.acos, Math.asin, Math.atan, Math.atan2, Math.cos, Math.sin


JavaScript语言参考手册_核心

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

Number

 Lets you work with numeric values. The Number object is an object wrapper for primitive numeric values.

Core object
实现版本Navigator 3.0, LiveWire 1.0
Navigator 4.0: modified behavior of Number constructor

创建源

The Number constructor:

new Number(value);

参数

valueThe numeric value of the object being created.

描述

The primary uses for the Number object are:

  • To access its constant properties, which represent the largest and smallest represen表 numbers, positive and negative infinity, and the Not-a-Number value.

  • To create numeric objects that you can add properties to. Most likely, you will rarely need to create a Number object.
The properties of Number are properties of the class itself, not of individual Number objects.

Navigator 4.0: Number(x) now produces NaN rather than an error if x is a string that does not contain a well-formed numeric literal. For example,

x=Number("three"); document.write(x + "<BR>"); prints NaN

属性概览

MAX_VALUE | The largest represen表 number.
MIN_VALUE | The smallest represen表 number.
NaN | Special "not a number" value.
NEGATIVE_INFINITY | Special infinite value; returned on overflow.
POSITIVE_INFINITY | Special negative infinite value; returned on overflow.
prototype | Allows the addition of properties to a Number object.

方法概览

toStringReturns a string representing the specified object.

示例

示例 1. The following example uses the Number object's properties to assign values to several numeric variables:

biggestNum = Number.MAX_VALUE
smallestNum = Number.MIN_VALUE
infiniteNum = Number.POSITIVE_INFINITY
negInfiniteNum = Number.NEGATIVE_INFINITY
notANum = Number.NaN
示例 2. The following example creates a Number object, myNum, then adds a描述 property to all Number objects. Then a value is assigned to the myNum object's描述 property.

myNum = new Number(65)
Number.prototype.description=null
myNum.description="wind speed"

属性

MAX_VALUE

 The maximum numeric value represen表 in JavaScript.

属性源 | Number
静态, 只读
实现版本 | Navigator 3,0, LiveWire 1.0

描述

The MAX_VALUE property has a value of approximately 1.79E+308. Values larger than MAX_VALUE are represented as "Infinity".

Because MAX_VALUE is a static property of Number, you always use it as Number.MAX_VALUE, rather than as a property of a Number object you created.

示例

The following code multiplies two numeric values. If the result is less than or equal to MAX_VALUE, the func1 function is called; otherwise, the func2 function is called.

if (num1 * num2 <= Number.MAX_VALUE)
func1()
else
func2()

MIN_VALUE

The smallest positive numeric value represen表 in JavaScript.

属性源 | Number
静态, 只读
实现版本 | Navigator 3,0, LiveWire 1.0

描述

The MIN_VALUE property is the number closest to 0, not the most negative number, that JavaScript can represent.

MIN_VALUE has a value of approximately 2.22E-308. Values smaller than MIN_VALUE ("underflow values") are converted to 0.

Because MIN_VALUE is a static property of Number, you always use it as Number.MIN_VALUE, rather than as a property of a Number object you created.

示例

The following code divides two numeric values. If the result is greater than or equal to MIN_VALUE, the func1 function is called; otherwise, the func2 function is called.

if (num1 / num2 >= Number.MIN_VALUE)
func1()
else
func2()

NaN

A special value representing Not-A-Number. This value is represented as the unquoted literal NaN.

属性源 | Number
只读 |
实现版本 | Navigator 3,0, LiveWire 1.0

描述

JavaScript prints the value Number.NaN as NaN.

NaN is always unequal to any other number, including NaN itself; you cannot check for the not-a-number value by comparing to Number.NaN. Use the isNaN function instead.

You might use the NaN property to indicate an error condition for a function that should return a valid number.

示例

In the following example, if month has a value greater than 12, it is assigned NaN, and a message is displayed indicating valid values.

var month = 13
if (month < 1 || month > 12) {
month = Number.NaN
alert("Month must be between 1 and 12.")
}

参看

isNaN, parseFloat, parseInt

NEGATIVE_INFINITY

A special numeric value representing negative infinity. This value is displayed as "-Infinity".

属性源 | Number
静态, 只读
实现版本 | Navigator 3,0, LiveWire 1.0

描述

This value behaves mathematically like infinity; for example, anything multiplied by infinity is infinity, and anything divided by infinity is 0.

Because NEGATIVE_INFINITY is a static property of Number, you always use it as Number.NEGATIVE_INFINITY, rather than as a property of a Number object you created.

示例

In the following example, the variable smallNumber is assigned a value that is smaller than the minimum value. When the if statement executes, smallNumber has the value "-Infinity", so the func1 function is called.

var smallNumber = -Number.MAX_VALUE*10
if (smallNumber == Number.NEGATIVE_INFINITY)
func1()
else
func2()

POSITIVE_INFINITY

A special numeric value representing infinity. This value is displayed as "Infinity".

属性源 | Number
静态, 只读
实现版本 | Navigator 3,0, LiveWire 1.0

描述

This value behaves mathematically like infinity; for example, anything multiplied by infinity is infinity, and anything divided by infinity is 0.

JavaScript does not have a literal for Infinity.

Because POSITIVE_INFINITY is a static property of Number, you always use it as Number.POSITIVE_INFINITY, rather than as a property of a Number object you created.

示例

In the following example, the variable bigNumber is assigned a value that is larger than the maximum value. When the if statement executes, bigNumber has the value "Infinity", so the func1 function is called.

var bigNumber = Number.MAX_VALUE * 10
if (bigNumber == Number.POSITIVE_INFINITY)
func1()
else
func2()

prototype

Represents the prototype for this class. You can use the prototype to add properties or methods to all instances of a class. For information on prototypes, see Function.prototype.

属性源 | Number
实现版本 | Navigator 3.0, LiveWire 1.0

方法

toString

 Returns a string representing the specified object.

方法源 | Number
实现版本 | Navigator 3.0

语法

toString()
toString(radix)

参数

radix(Optional) An integer between 2 and 16 specifying the base to use for representing numeric values.

描述

Every object has a toString method that is automatically called when it is to be represented as a text value or when an object is referred to in a string concatenation.

You can use toString within your own code to convert an object into a string, and you can create your own function to be called in place of the default toString method.

You can use toString on numeric values, but not on numeric literals:

// The next two lines are valid
var howMany=10
document.write("howMany.toString() is " + howMany.toString() + "<BR>") // The next line causes an error
document.write("45.toString() is " + 45.toString() + "<BR>") For information on defining your own toString method, see the Object.toString method.


JavaScript语言参考手册_核心

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

Object

 Object is the primitive JavaScript object type. All JavaScript objects are descended from Object. That is, all JavaScript objects have the methods defined for Object.

Core object
实现版本Navigator 2.0: toString 方法
Navigator 3.0, LiveWire 1.0: 添加了 eval and valueOf 方法s; constructor 属性
Navigator 3.0: removed eval 方法

创建源

The Object constructor:

new Object();

参数

无

属性概览

constructor | Specifies the function that creates an object's prototype.
prototype | Allows the addition of properties to all objects.

方法概览

eval | Evaluates a string of JavaScript code in the context of the specified object.
toString | Returns a string representing the specified object.
unwatch | Removes a watchpoint from a 属性源 the object.
valueOf | Returns the primitive value of the specified object.
watch | Adds a watchpoint to a 属性源 the object.

属性

constructor

 Specifies the function that creates an object's prototype. Note that the value of this property is a reference to the function itself, not a string containing the function's name.

属性源 | Object
实现版本 | Navigator 3.0, LiveWire 1.0

描述

All objects inherit a constructor property from their prototype:

o = new Object // or o = {} in Navigator 4.0
o.constructor == Object
a = new Array // or a = [] in Navigator 4.0
a.constructor == Array
n = new Number(3)
n.constructor == Number Even though you cannot construct most HTML objects, you can do comparisons. For example,

document.constructor == Document
document.form3.constructor == Form

示例

The following example creates a prototype, Tree, and an object of that type, theTree. The example then displays the constructor property for the object theTree.

function Tree(name) {
this.name=name
}
theTree = new Tree("Redwood")
document.writeln("<B>theTree.constructor is</B> " +
theTree.constructor + "<P>") This example displays the following output:

theTree.constructor is function Tree(name) { this.name = name; }

prototype

Represents the prototype for this class. You can use the prototype to add properties or methods to all instances of a class. For more information, see Function.prototype.

属性源 | Object
实现版本 | Navigator 3.0

方法

eval

 Evaluates a string of JavaScript code in the context of this object.

方法源 | Object
实现版本 | Navigator 3.0, LiveWire 1.0 Navigator 4.0, Netscape Server 3.0: removed as 方法源 objects; retained as global function.

语法

eval(string)

参数

stringAny string representing a JavaScript expression, statement, or sequence of statements. The expression can include variables and properties of existing objects.

描述

The argument of the eval method is a string. If the string represents an expression, eval evaluates the expression. If the argument represents one or more JavaScript statements, eval performs the statements. Do not call eval to evaluate an arithmetic expression; JavaScript evaluates arithmetic expressions automatically.

If you construct an arithmetic expression as a string, you can use eval to evaluate it at a later time. For example, suppose you have a variable x. You can postpone evaluation of an expression involving x by assigning the string value of the expression, say "3 * x + 2", to a variable, and then calling eval at a later point in your script.

eval is also a global function, not associated with any object.

NOTE: In Navigator 2.0, eval was a top-level function. In Navigator 3.0 eval was also a method of every object. The ECMA-262 standard for JavaScript made eval available only as a top-level function. For this reason, in Navigator 4.0, eval is once again a top-level function. In Navigator 4.02, obj.eval(str) is equivalent in all scopes to with(obj)eval(str), except of course that the latter is a statement, not an expression.

示例

 示例 1. The following example creates breed as a property of the object myDog, and also as a variable. The first write statement uses eval('breed') without specifying an object; the string "breed" is evaluated without regard to any object, and the write method displays "Shepherd", which is the value of the breed variable. The second write statement uses myDog.eval('breed') which specifies the object myDog; the string "breed" is evaluated with regard to the myDog object, and the write method displays "Lab", which is the value of the breed property of the myDog object.

function Dog(name,breed,color) {
this.name=name
this.breed=breed
this.color=color
}
myDog = new Dog("Gabby")
myDog.breed="Lab"
var breed='Shepherd'
document.write("<P>" + eval('breed'))
document.write("<BR>" + myDog.eval('breed'))
示例 2. The following example uses eval within a function that defines an object type, stone. The statement flint = new stone("x=42") creates the object flint with the properties x, y, z, and z2. The write statements display the values of these properties as 42, 43, 44, and 45, respectively.

function stone(str) {
this.eval("this."+str)
this.eval("this.y=43")
this.z=44
this["z2"] = 45
}
flint = new stone("x=42")
document.write("<BR>flint.x is " + flint.x)
document.write("<BR>flint.y is " + flint.y)
document.write("<BR>flint.z is " + flint.z)
document.write("<BR>flint.z2 is " + flint.z2)

参看

eval

toString

Returns a string representing the specified object.

方法源 | Object
实现版本 | Navigator 2.0

语法

toString()
toString(radix)

参数

radix(Optional) An integer between 2 and 16 specifying the base to use for representing numeric values.

安全性

Navigator 3.0: This method is tainted by default for the following objects: Button, Checkbox, FileUpload, Hidden, History, Link, Location, Password, Radio, Reset, Select, Submit, Text, and Textarea.

For information on data tainting, see "JavaScript Security".

描述

Every object has a toString method that is automatically called when it is to be represented as a text value or when an object is referred to in a string concatenation. For example, the following示例 require theDog to be represented as a string:

document.write(theDog)
document.write("The dog is " + theDog) You can use toString within your own code to convert an object into a string, and you can create your own function to be called in place of the default toString method.

Built-in toString methods
Every object type has a built-in toString method, which JavaScript calls whenever it needs to convert an object to a string. If an object has no string value and no user-defined toString method, toString returns "[object type]", where type is the object type or the name of the constructor function that created the object. For example, if for an Image object named sealife defined as shown below, sealife.toString() returns [object Image].

<IMG NAME="sealife" SRC="images\seaotter.gif" ALIGN="left" VSPACE="10"> Some built-in classes have special definitions for their toString methods. See the描述s of this method for these objects:

Array, Boolean, Connection, database, DbPool, Function, Number

User-defined toString methods
You can create a function to be called in place of the default toString method. The toString method takes no arguments and should return a string. The toString method you create can be any value you want, but it will be most useful if it carries information about the object.

The following code defines the Dog object type and creates theDog, an object of type Dog:

function Dog(name,breed,color,sex) {
this.name=name
this.breed=breed
this.color=color
this.sex=sex
}
theDog = new Dog("Gabby","Lab","chocolate","girl")
The following code creates dogToString, the function that will be used in place of the default toString method. This function generates a string containing each property, of the form "property = value;".

function dogToString() {
var ret = "Dog " + this.name + " is ["
for (var prop in this)
ret += "  " + prop + " is " + this[prop] + ";"
return ret + "]"
}
The following code assigns the user-defined function to the object's toString method:

Dog.prototype.toString = dogToString With the preceding code in place, any time theDog is used in a string context, JavaScript automatically calls the dogToString function, which returns the following string:

Dog Gabby is [ name is Gabby; breed is Lab; color is chocolate; sex is girl;
toString is function dogToString() { var ret = "Object " + this.name + " is [";
for (var prop in this) { ret += " " + prop + " is " + this[prop] + ";"; } return ret
+ "]"; } ;]
An object's toString method is usually invoked by JavaScript, but you can invoke it yourself as follows:

alert(theDog.toString())

示例

示例 1: The location object. The following example prints the string equivalent of the current location.

document.write("location.toString() is " + location.toString() + "<BR>") The output is as follows:

location.toString() is file:///C|/TEMP/myprog.html 示例 2: Object with no string value. Assume you have an Image object named sealife defined as follows:

<IMG NAME="sealife" SRC="images\seaotter.gif" ALIGN="left" VSPACE="10"> Because the Image object itself has no special toString method, sealife.toString() returns the following:

[object Image] 示例 3: The radix parameter. The following example prints the string equivalents of the numbers 0 through 9 in decimal and binary.

for (x = 0; x < 10; x++) {
document.write("Decimal: ", x.toString(10), " Binary: ",
x.toString(2), "<BR>")
}
The preceding example produces the following output:

Decimal: 0 Binary: 0
Decimal: 1 Binary: 1
Decimal: 2 Binary: 10
Decimal: 3 Binary: 11
Decimal: 4 Binary: 100
Decimal: 5 Binary: 101
Decimal: 6 Binary: 110
Decimal: 7 Binary: 111
Decimal: 8 Binary: 1000
Decimal: 9 Binary: 1001

参看

Object.valueOf

unwatch

Removes a watchpoint set with the watch method.

方法源 | Object
实现版本 | Navigator 4.0, Netscape Server 3.0

语法

unwatch(prop)

参数

propThe name of a 属性源 the object.

描述

The JavaScript debugger has functionality similar to that provided by this method, as well as other debugging options. For information on the debugger, see Getting Started with Netscape JavaScript Debugger.

示例

See watch.

valueOf

Returns the primitive value of the specified object.

方法源 | Object
实现版本 | Navigator 3.0

语法

valueOf()

参数

 无

描述

Every object has a valueOf method that is automatically called when it is to be represented as a primitive value. If an object has no primitive value, valueOf returns the object itself.

You can use valueOf within your own code to convert an object into a primitive value, and you can create your own function to be called in place of the default valueOf method.

Every object type has a built-in valueOf method, which JavaScript calls whenever it needs to convert an object to a primitive value.

You rarely need to invoke the valueOf method yourself. JavaScript automatically invokes it when encountering an object where a primitive value is expected.

表 4.2 shows the object types for which the valueOf method is most useful. Most other objects have no primitive value.

表 4.2 Use valueOf for these object types
对象 type | Value returned by valueOf
Number | Primitive numeric value associated with the object.
Boolean | Primitive boolean value associated with the object.
String | String associated with the object.
Function | Function reference associated with the object. For example, typeof funObj returns "object", but typeof funObj.valueOf() returns "function".

You can create a function to be called in place of the default valueOf method. Your function must take no arguments.

Suppose you have an object type myNumberType and you want to create a valueOf method for it. The following code assigns a user-defined function to the object's valueOf method:

myNumberType.prototype.valueOf = new Function(functionText) With the preceding code in place, any time an object of type myNumberType is used in a context where it is to be represented as a primitive value, JavaScript automatically calls the function defined in the preceding code.

An object's valueOf method is usually invoked by JavaScript, but you can invoke it yourself as follows:

myNumber.valueOf()

NOTE: Objects in string contexts convert via the toString method, which is different from String objects converting to string primitives using valueOf. All string objects have a string conversion, if only "[object type]". But many objects do not convert to number, boolean, or function.

参看

 parseInt, Object.toString

watch

Watches for a property to be assigned a value and runs a function when that occurs.

方法源 | Object
实现版本 | Navigator 4.0, Netscape Server 3.0

语法

watch(prop, handler)

参数

prop | The name of a 属性源 the object.
handler | A function to call.

描述

Watches for assignment to a property named prop in this object, calling handler(prop, oldval, newval) whenever prop is set and storing the return value in that property. A watchpoint can filter (or nullify) the value assignment, by returning a modified newval (or oldval).

If you delete a property for which a watchpoint has been set, that watchpoint does not disappear. If you later recreate the property, the watchpoint is still in effect.

To remove a watchpoint, use the unwatch method.

The JavaScript debugger has functionality similar to that provided by this method, as well as other debugging options. For information on the debugger, see Getting Started with Netscape JavaScript Debugger.

示例

<script language="JavaScript1.2">
o = {p:1}
o.watch("p",
function (id,oldval,newval) {
document.writeln("o." + id + " changed from "
+ oldval + " to " + newval)
return newval
}) o.p = 2
o.p = 3
delete o.p
o.p = 4 o.unwatch('p')
o.p = 5 </script> This script displays the following:

o.p changed from 1 to 2
o.p changed from 2 to 3
o.p changed from 3 to 4


JavaScript语言参考手册_核心

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

String

 An object representing a series of characters in a string.

Core object
实现版本Navigator 2.0: Create a String object only by quoting characters.
Navigator 3.0, LiveWire 1.0: 添加了 String constructor; 添加了 prototype 属性; 添加了 split 方法; 添加了 ability to pass strings among scripts in different windows or frames (in previous releases, you had to add an empty string to another window's string to refer to it)
Navigator 4.0, Netscape Server 3.0: 添加了 concat, match, replace, search, slice, and substr 方法s.

创建源

The String constructor:

new String(string);

参数

stringAny string.

描述

The String object is a built-in JavaScript object. You an treat any JavaScript string as a String object.

A string can be represented as a literal enclosed by single or double quotation marks; for example, "Netscape" or 'Netscape'.

属性概览

length | Reflects the length of the string.
prototype | Allows the addition of properties to a String object.

方法概览

anchor | Creates an HTML anchor that is used as a hypertext target.
big | Causes a string to be displayed in a big font as if it were in a BIG tag.
blink | Causes a string to blink as if it were in a BLINK tag.
bold | Causes a string to be displayed as if it were in a B tag.
charAt | Returns the character at the specified index.
charCodeAt | Returns a number indicating the ISO-Latin-1 codeset value of the character at the given index.
concat | Combines the text of two strings and returns a new string.
fixed | Causes a string to be displayed in fixed-pitch font as if it were in a TT tag.
fontcolor | Causes a string to be displayed in the specified color as if it were in a <FONT COLOR=color> tag.
fontsize | Causes a string to be displayed in the specified font size as if it were in a <FONT SIZE=size> tag.
fromCharCode | Returns a string from the specified sequence of numbers that areISO-Latin-1 codeset values.
indexOf | Returns the index within the calling String object of the first occurrence of the specified value.
italics | Causes a string to be italic, as if it were in an I tag.
lastIndexOf | Returns the index within the calling String object of the last occurrence of the specified value.
link | Creates an HTML hypertext link that requests another URL.
match | Used to match a regular expression against a string.
replace | Used to find a match between a regular expression and a string, and to replace the matched substring with a new substring.
search | Executes the search for a match between a regular expression and a specified string.
slice | Extracts a section of a string and returns a new string.
small | Causes a string to be displayed in a small font, as if it were in a SMALL tag.
split | Splits a String object into an array of strings by separating the string into substrings.
strike | Causes a string to be displayed as struck-out text, as if it were in a STRIKE tag.
sub | Causes a string to be displayed as a subscript, as if it were in a SUB tag.
substr | Returns the characters in a string beginning at the specified location through the specified number of characters.
substring | Returns the characters in a string between two indexes into the string.
sup | Causes a string to be displayed as a superscript, as if it were in a SUP tag.
toLowerCase | Returns the calling string value converted to lowercase.
toUpperCase | Returns the calling string value converted to uppercase.

示例

示例 1: String variable. The following statement creates a string variable:

var last_name = "Schaefer" 示例 2: String object properties. The following statements evaluate to 8, "SCHAEFER," and "schaefer":

last_name.length
last_name.toUpperCase()
last_name.toLowerCase() 示例 3: Accessing individual characters in a string. You can think of a string as an array of characters. In this way, you can access the individual characters in the string by indexing that array. For example, the following code:

var myString = "Hello"
document.write ("The first character in the string is " + myString[0]) displays "The first character in the string is H"

示例 4: Pass a string among scripts in different windows or frames. The following code creates two string variables and opens a second window:

var lastName = new String("Schaefer")
var firstName = new String ("Jesse")
empWindow=window.open('string2.html','window1','width=300,height=300')
If the HTML source for the second window (string2.html) creates two string variables, empLastName and empFirstName, the following code in the first window assigns values to the second window's variables:

empWindow.empFirstName=firstName
empWindow.empLastName=lastName The following code in the first window displays the values of the second window's variables:

alert('empFirstName in empWindow is ' + empWindow.empFirstName)
alert('empLastName in empWindow is ' + empWindow.empLastName)

属性

length

 The length of the string.

属性源 | String
只读
实现版本 | Navigator 2.0, LiveWire 1.0

描述

For a null string, length is 0.

示例

The following example displays 8 in an Alert dialog box:

var x="Netscape"
alert("The string length is " + x.length)

prototype

Represents the prototype for this class. You can use the prototype to add properties or methods to all instances of a class. For information on prototypes, see Function.prototype.

属性源 | String
实现版本 | Navigator 3.0, Netscape Server 3.0

方法

anchor

 Creates an HTML anchor that is used as a hypertext target.

方法源 | String
实现版本 | Navigator 2.0, LiveWire 1.0

语法

anchor(nameAttribute)

参数

nameAttributeA string.

描述

Use the anchor method with the document.write or document.writeln methods to programmatically create and display an anchor in a document. Create the anchor with the anchor method, and then call write or writeln to display the anchor in a document. In server-side JavaScript, use the write function to display the anchor.

In the语法, the text string represents the literal text that you want the user to see. The nameAttribute string represents the NAME attribute of the A tag.

Anchors created with the anchor method become elements in the document.anchors array.

示例

The following example opens the msgWindow window and creates an anchor for the 表 of contents:

var myString="表 of Contents"
msgWindow.document.writeln(myString.anchor("contents_anchor")) The previous example produces the same output as the following HTML:

<A NAME="contents_anchor">表 of Contents</A> In server-side JavaScript, you can generate this HTML by calling the write function instead of using document.writeln.

参看

String.link

big

Causes a string to be displayed in a big font as if it were in a BIG tag.

方法源 | String
实现版本 | Navigator 2.0, LiveWire 1.0

语法

big()

参数

 无

描述

Use the big method with the write or writeln methods to format and display a string in a document. In server-side JavaScript, use the write function to display the string.

示例

The following example uses string methods to change the size of a string:

var worldString="Hello, world"
document.write(worldString.small())
document.write("<P>" + worldString.big())
document.write("<P>" + worldString.fontsize(7))
The previous example produces the same output as the following HTML:

<SMALL>Hello, world</SMALL>
<P><BIG>Hello, world</BIG>
<P><FONTSIZE=7>Hello, world</FONTSIZE>

参看

String.fontsize, String.small

blink

Causes a string to blink as if it were in a BLINK tag.

方法源 | String
实现版本 | Navigator 2.0, LiveWire 1.0

语法

blink()

参数

 无

描述

Use the blink method with the write or writeln methods to format and display a string in a document. In server-side JavaScript, use the write function to display the string.

示例

The following example uses string methods to change the formatting of a string:

var worldString="Hello, world"
document.write(worldString.blink())
document.write("<P>" + worldString.bold())
document.write("<P>" + worldString.italics())
document.write("<P>" + worldString.strike())
The previous example produces the same output as the following HTML:

<BLINK>Hello, world</BLINK>
<P><B>Hello, world</B>
<P><I>Hello, world</I>
<P><STRIKE>Hello, world</STRIKE>

参看

String.bold, String.italics, String.strike

bold

Causes a string to be displayed as bold as if it were in a B tag.

方法源 | String
实现版本 | Navigator 2.0, LiveWire 1.0

语法

bold()

参数

 无

描述

Use the bold method with the write or writeln methods to format and display a string in a document. In server-side JavaScript, use the write function to display the string.

示例

The following example uses string methods to change the formatting of a string:

var worldString="Hello, world"
document.write(worldString.blink())
document.write("<P>" + worldString.bold())
document.write("<P>" + worldString.italics())
document.write("<P>" + worldString.strike())
The previous example produces the same output as the following HTML:

<BLINK>Hello, world</BLINK>
<P><B>Hello, world</B>
<P><I>Hello, world</I>
<P><STRIKE>Hello, world</STRIKE>

参看

String.blink, String.italics, String.strike

charAt

Returns the specified character from the string.

方法源 | String
实现版本 | Navigator 2.0, LiveWire 1.0

语法

charAt(index)

参数

indexAn integer between 0 and 1 less than the length of the string.

描述

Characters in a string are indexed from left to right. The index of the first character is 0, and the index of the last character in a string called stringName is stringName.length - 1. If the index you supply is out of range, JavaScript returns an empty string.

示例

The following example displays characters at different locations in the string "Brave new world":

var anyString="Brave new world" document.writeln("The character at index 0 is " + anyString.charAt(0))
document.writeln("The character at index 1 is " + anyString.charAt(1))
document.writeln("The character at index 2 is " + anyString.charAt(2))
document.writeln("The character at index 3 is " + anyString.charAt(3))
document.writeln("The character at index 4 is " + anyString.charAt(4)) These lines display the following:

The character at index 0 is B
The character at index 1 is r
The character at index 2 is a
The character at index 3 is v
The character at index 4 is e

In server-side JavaScript, you can display the same output by calling the write function instead of using document.write.

参看

String.indexOf, String.lastIndexOf, String.split

charCodeAt

Returns a number indicating the ISO-Latin-1 codeset value of the character at the given index.

方法源 | String
实现版本 | Navigator 4.0, Netscape Server 3.0

语法

charCodeAt(index)

参数

index(Optional) An integer between 0 and 1 less than the length of the string. The default value is 0.

描述

The ISO-Latin-1 codeset ranges from 0 to 255. The first 0 to 127 are a direct match of the ASCII character set.

示例

The following example returns 65, the ISO-Latin-1 codeset value for A.

"ABC".charCodeAt(0)

concat

Combines the text of two strings and returns a new string.

方法源 | String
实现版本 | Navigator 4.0, Netscape Server 3.0

语法

concat(string2)

参数

string1 | The first string.
string2 | The second string.

描述

concat combines the text from two strings and returns a new string. Changes to the text in one string do not affect the other string.

示例

The following example combines two strings into a new string.

<SCRIPT>
str1="The morning is upon us. "
str2="The sun is bright."
str3=str1.concat(str2)
document.writeln(str1)
document.writeln(str2)
document.writeln(str3)
</SCRIPT>
This writes:

The morning is upon us.
The sun is bright.
The morning is upon us. The sun is bright.

fixed

Causes a string to be displayed in fixed-pitch font as if it were in a TT tag.

方法源 | String
实现版本 | Navigator 2.0, LiveWire 1.0

语法

fixed()

参数

 无

描述

Use the fixed method with the write or writeln methods to format and display a string in a document. In server-side JavaScript, use the write function to display the string.

示例

The following example uses the fixed method to change the formatting of a string:

var worldString="Hello, world"
document.write(worldString.fixed()) The previous example produces the same output as the following HTML:

<TT>Hello, world</TT>

fontcolor

Causes a string to be displayed in the specified color as if it were in a <FONT COLOR=color> tag.

方法源 | String
实现版本 | Navigator 2.0, LiveWire 1.0

语法

fontcolor(color)

参数

color A string expressing the color as a hexadecimal RGB triplet or as a string literal. String literals for color names are listed in Appendix B, "Color Values," in the JavaScript Guide.

描述

Use the fontcolor method with the write or writeln methods to format and display a string in a document. In server-side JavaScript, use the write function to display the string.

If you express 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 fontcolor method overrides a value set in the fgColor property.

示例

The following example uses the fontcolor method to change the color of a string:

var worldString="Hello, world" document.write(worldString.fontcolor("maroon") +
" is maroon in this line")
document.write("<P>" + worldString.fontcolor("salmon") +
" is salmon in this line")
document.write("<P>" + worldString.fontcolor("red") +
" is red in this line") document.write("<P>" + worldString.fontcolor("8000") +
" is maroon in hexadecimal in this line")
document.write("<P>" + worldString.fontcolor("FA8072") +
" is salmon in hexadecimal in this line")
document.write("<P>" + worldString.fontcolor("FF00") +
" is red in hexadecimal in this line") The previous example produces the same output as the following HTML:

<FONT COLOR="maroon">Hello, world</FONT> is maroon in this line
<P><FONT COLOR="salmon">Hello, world</FONT> is salmon in this line
<P><FONT COLOR="red">Hello, world</FONT> is red in this line
<FONT COLOR="8000">Hello, world</FONT>
is maroon in hexadecimal in this line
<P><FONT COLOR="FA8072">Hello, world</FONT>
is salmon in hexadecimal in this line
<P><FONT COLOR="FF00">Hello, world</FONT>
is red in hexadecimal in this line

fontsize

Causes a string to be displayed in the specified font size as if it were in a <FONT SIZE=size> tag.

方法源 | String
实现版本 | Navigator 2.0, LiveWire 1.0

语法

fontsize(size)

参数

sizeAn integer between 1 and 7, a string representing a signed integer between 1 and 7.

描述

Use the fontsize method with the write or writeln methods to format and display a string in a document. In server-side JavaScript, use the write function to display the string.

When you specify size as an integer, you set the size of stringName to one of the 7 defined sizes. When you specify size as a string such as "-2", you adjust the font size of stringName relative to the size set in the BASEFONT tag.

示例

The following example uses string methods to change the size of a string:

var worldString="Hello, world"
document.write(worldString.small())
document.write("<P>" + worldString.big())
document.write("<P>" + worldString.fontsize(7))
The previous example produces the same output as the following HTML:

<SMALL>Hello, world</SMALL>
<P><BIG>Hello, world</BIG>
<P><FONTSIZE=7>Hello, world</FONTSIZE>

参看

String.big, String.small

fromCharCode

Returns a string created by using the specified sequence ISO-Latin-1 codeset values.

方法源 | String
静态
实现版本 | Navigator 4.0, Netscape Server 3.0

语法

fromCharCode(num1, ..., numN)

参数

num1, ..., numNA sequence of numbers that are ISO-Latin-1 codeset values.

描述

This method returns a string and not a String object.

Because fromCharCode is a static method of String, you always use it as String.fromCharCode(), rather than as a method of a String object you created.

示例

示例 1. The following example returns the string "ABC".

String.fromCharCode(65,66,67) 示例 2. The which property of the KeyDown, KeyPress, and KeyUp events contains the ASCII value of the key pressed at the time the event occurred. If you want to get the actual letter, number, or symbol of the key, you can use fromCharCode. The following example returns the letter, number, or symbol of the KeyPress event's which property.

String.fromCharCode(KeyPress.which)

indexOf

Returns the index within the calling String object of the first occurrence of the specified value, starting the search at fromIndex, or -1 if the value is not found.

方法源 | String
实现版本 | Navigator 2.0, LiveWire 1.0

语法

indexOf(searchValue, fromIndex)

参数

searchValue | A string representing the value to search for.
fromIndex | (Optional) The location within the calling string to start the search from. It can be any integer between 0 and 1 less than the length of the string. The default value is 0.

描述

Characters in a string are indexed from left to right. The index of the first character is 0, and the index of the last character of a string called stringName is stringName.length - 1.

If stringName contains an empty string (""), indexOf returns an empty string.

The indexOf method is case sensitive. For example, the following expression returns -1:

"Blue Whale".indexOf("blue")

示例

示例 1. The following example uses indexOf and lastIndexOf to locate values in the string "Brave new world."

var anyString="Brave new world" //Displays 8
document.write("<P>The index of the first w from the beginning is " +
anyString.indexOf("w"))
//Displays 10
document.write("<P>The index of the first w from the end is " +
anyString.lastIndexOf("w"))
//Displays 6
document.write("<P>The index of 'new' from the beginning is " +
anyString.indexOf("new"))
//Displays 6
document.write("<P>The index of 'new' from the end is " +
anyString.lastIndexOf("new")) 示例 2. The following example defines two string variables. The variables contain the same string except that the second string contains uppercase letters. The first writeln method displays 19. But because the indexOf method is case sensitive, the string "cheddar" is not found in myCapString, so the second writeln method displays -1.

myString="brie, pepper jack, cheddar"
myCapString="Brie, Pepper Jack, Cheddar"
document.writeln('myString.indexOf("cheddar") is ' +
myString.indexOf("cheddar"))
document.writeln('<P>myCapString.indexOf("cheddar") is ' +
myCapString.indexOf("cheddar"))
示例 3. The following example sets count to the number of occurrences of the letter x in the string str:

count = 0;
pos = str.indexOf("x");
while ( pos != -1 ) {
count++;
pos = str.indexOf("x",pos+1);
}

参看

String.charAt, String.lastIndexOf, String.split

italics

Causes a string to be italic, as if it were in an I tag.

方法源 | String
实现版本 | Navigator 2.0, LiveWire 1.0

语法

italics()

参数

 无

描述

Use the italics method with the write or writeln methods to format and display a string in a document. In server-side JavaScript, use the write function to display the string.

示例

The following example uses string methods to change the formatting of a string:

var worldString="Hello, world"
document.write(worldString.blink())
document.write("<P>" + worldString.bold())
document.write("<P>" + worldString.italics())
document.write("<P>" + worldString.strike())
The previous example produces the same output as the following HTML:

<BLINK>Hello, world</BLINK>
<P><B>Hello, world</B>
<P><I>Hello, world</I>
<P><STRIKE>Hello, world</STRIKE>

参看

String.blink, String.bold, String.strike

lastIndexOf

Returns the index within the calling String object of the last occurrence of the specified value. The calling string is searched backward, starting at fromIndex, or -1 if not found.

方法源 | String
实现版本 | Navigator 2.0, LiveWire 1.0

语法

lastIndexOf(searchValue, fromIndex)

参数

searchValue | A string representing the value to search for.
fromIndex | (Optional) The location within the calling string to start the search from. It can be any integer between 0 and 1 less than the length of the string. The default value is 1 less than the length of the string.

描述

Characters in a string are indexed from left to right. The index of the first character is 0, and the index of the last character is stringName.length - 1.

The lastIndexOf method is case sensitive. For example, the following expression returns -1:

"Blue Whale, Killer Whale".lastIndexOf("blue")

示例

The following example uses indexOf and lastIndexOf to locate values in the string "Brave new world."

var anyString="Brave new world" //Displays 8
document.write("<P>The index of the first w from the beginning is " +
anyString.indexOf("w"))
//Displays 10
document.write("<P>The index of the first w from the end is " +
anyString.lastIndexOf("w"))
//Displays 6
document.write("<P>The index of 'new' from the beginning is " +
anyString.indexOf("new"))
//Displays 6
document.write("<P>The index of 'new' from the end is " +
anyString.lastIndexOf("new")) In server-side JavaScript, you can display the same output by calling the write function instead of using document.write.

参看

String.charAt, String.indexOf, String.split

link

Creates an HTML hypertext link that requests another URL.

方法源 | String
实现版本 | Navigator 2.0, LiveWire 1.0

语法

link(hrefAttribute)

参数

hrefAttributeAny string that specifies the HREF attribute of the A tag; it should be a valid URL (relative or absolute).

描述

Use the link method to programmatically create a hypertext link, and then call write or writeln to display the link in a document. In server-side JavaScript, use the write function to display the link.

Links created with the link method become elements in the links array of the document object. See document.links.

示例

The following example displays the word "Netscape" as a hypertext link that returns the user to the Netscape home page:

var hotText="Netscape"
var URL="http://home.netscape.com" document.write("Click to return to " + hotText.link(URL)) The previous example produces the same output as the following HTML:

Click to return to <A HREF="http://home.netscape.com">Netscape</A>

参看

Anchor

match

Used to match a regular expression against a string.

方法源 | String
实现版本 | Navigator 4.0

语法

match(regexp)

参数

regexpName of the regular expression. It can be a variable name or a literal.

描述

If you want to execute a global match, or a case insensitive match, include the g (for global) and i (for ignore case) flags in the regular expression. These can be included separately or together. The following two示例 below show how to use these flags with match.

Note

If you execute a match simply to find true or false, use String.search or the regular expression test method.

示例

示例 1. In the following example, match is used to find 'Chapter' followed by 1 or more numeric characters followed by a decimal point and numeric character 0 or more times. The regular expression includes the i flag so that case will be ignored.

<SCRIPT>
str = "For more information, see Chapter 3.4.5.1";
re = /(chapter \d+(\.\d)*)/i;
found = str.match(re);
document.write(found);
</SCRIPT> This returns the array containing Chapter 3.4.5.1,Chapter 3.4.5.1,.1

'Chapter 3.4.5.1' is the first match and the first value remembered from (Chapter \d+(\.\d)*).

'.1' is the second value remembered from (\.\d).

示例 2. The following example demonstrates the use of the global and ignore case flags with match.

<SCRIPT>
str = "abcDdcba";
newArray = str.match(/d/gi);
document.write(newArray);
</SCRIPT> The returned array contains D, d.

replace

Used to find a match between a regular expression and a string, and to replace the matched substring with a new substring.

方法源 | String
实现版本 | Navigator 4.0

语法

replace(regexp, newSubStr)

参数

regexp | The name of the regular expression. It can be a variable name or a literal.
newSubStr | The string to put in place of the string found with regexp. This string can include the RegExp properties $1, ..., $9, lastMatch, lastParen, leftContext, and rightContext.

描述

This method does not change the String object it is called on; it simply returns a new string.

If you want to execute a global search and replace, or a case insensitive search, include the g (for global) and i (for ignore case) flags in the regular expression. These can be included separately or together. The following two示例 below show how to use these flags with replace.

示例

示例 1. In the following example, the regular expression includes the global and ignore case flags which permits replace to replace each occurrence of 'apples' in the string with 'oranges.'

<SCRIPT>
re = /apples/gi;
str = "Apples are round, and apples are juicy.";
newstr=str.replace(re, "oranges");
document.write(newstr)
</SCRIPT> This prints "oranges are round, and oranges are juicy."

示例 2. In the following example, the regular expression is defined in replace and includes the ignore case flag.

<SCRIPT>
str = "Twas the night before Xmas...";
newstr=str.replace(/xmas/i, "Christmas");
document.write(newstr)
</SCRIPT> This prints "Twas the night before Christmas..."

示例 3. The following script switches the words in the string. For the replacement text, the script uses the values of the $1 and $2 properties.

<SCRIPT LANGUAGE="JavaScript1.2">
re = /(\w+)\s(\w+)/;
str = "John Smith";
newstr = str.replace(re, "$2, $1");
document.write(newstr)
</SCRIPT>
This prints "Smith, John".

search

Executes the search for a match between a regular expression and this String object.

方法源 | String
实现版本 | Navigator 4.0

语法

search(regexp)

参数

regexpName of the regular expression. It can be a variable name or a literal.

描述

If successful, search returns the index of the regular expression inside the string. Otherwise, it returns -1.

When you want to know whether a pattern is found in a string use search (similar to the regular expression test method); for more information (but slower execution) use match (similar to the regular expression exec method).

示例

The following example prints a message which depends on the success of the test.

function testinput(re, str){
if (str.search(re) != -1)
midstring = " contains ";
else
midstring = " does not contain ";
document.write (str + midstring + re.source);
}

slice

Extracts a section of a string and returns a new string.

方法源 | String
实现版本 | Navigator 2.0, LiveWire 1.0

语法

slice(beginslice,endSlice)

参数

beginSlice | The zero-based index at which to begin extraction.
endSlice | (Optional) The zero-based index at which to end extraction. If omitted, slice extracts to the end of the string.

描述

slice extracts the text from one string and returns a new string. Changes to the text in one string do not affect the other string.

slice extracts up to but not including endSlice. string.slice(1,4) extracts the second character through the fourth character (characters indexed 1, 2, and 3).

As a negative index, endSlice indicates an offset from the end of the string. string.slice(2,-1) extracts the third character through the second to last character in the string.

示例

The following example uses slice to create a new string.

<SCRIPT>
str1="The morning is upon us. "
str2=str1.slice(3,-5)
document.write(str2)
</SCRIPT> This writes:

morning is upon

small

Causes a string to be displayed in a small font, as if it were in a SMALL tag.

方法源 | String
实现版本 | Navigator 2.0, LiveWire 1.0

语法

small()

参数

 无

描述

Use the small method with the write or writeln methods to format and display a string in a document. In server-side JavaScript, use the write function to display the string.

示例

The following example uses string methods to change the size of a string:

var worldString="Hello, world"
document.write(worldString.small())
document.write("<P>" + worldString.big())
document.write("<P>" + worldString.fontsize(7))
The previous example produces the same output as the following HTML:

<SMALL>Hello, world</SMALL>
<P><BIG>Hello, world</BIG>
<P><FONTSIZE=7>Hello, world</FONTSIZE>

参看

String.big, String.fontsize

split

Splits a String object into an array of strings by separating the string into substrings.

方法源 | String
实现版本 | Navigator 3.0, LiveWire 1.0

语法

split(separator, limit)

参数

separator | (Optional) Specifies the character to use for separating the string. The separator is treated as a string. If separator is omitted, the array returned contains one element consisting of the entire string.
limit | (Optional) Integer specifying a limit on the number of splits to be found.

描述

The split method returns the new array.

When found, separator is removed from the string and the substrings are returned in an array. If separator is omitted, the array contains one element consisting of the entire string.

In Navigator 4.0, Split has the following additions:

  • It can take a regular expression argument, as well as a fixed string, by which to split the object string. If separator is a regular expression, any included parenthesis cause submatches to be included in the returned array.

  • It can take a limit count so that it won't include trailing empty elements in the resulting array.

  • If you specify LANGUAGE="JavaScript1.2" in the SCRIPT tag, string.split(" ") splits on any run of 1 or more white space characters including spaces, tabs, line feeds, and carriage returns.

示例

 示例 1. The following example defines a function that splits a string into an array of strings using the specified separator. After splitting the string, the function displays messages indicating the original string (before the split), the separator used, the number of elements in the array, and the individual array elements.

function splitString (stringToSplit,separator) {
arrayOfStrings = stringToSplit.split(separator)
document.write ('<P>The original string is: "' + stringToSplit + '"')
document.write ('<BR>The separator is: "' + separator + '"')
document.write ("<BR>The array has " + arrayOfStrings.length + " elements: ")
   for (var i=0; i < arrayOfStrings.length; i++) {
document.write (arrayOfStrings[i] + " / ")
}
}
var tempestString="Oh brave new world that has such people in it."
var monthString="Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec"
var space=" "
var comma=","
splitString(tempestString,space)
splitString(tempestString)
splitString(monthString,comma)
This example produces the following output:

The original string is: "Oh brave new world that has such people in it."
The separator is: " "
The array has 10 elements: Oh / brave / new / world / that / has / such / people / in / it. / The original string is: "Oh brave new world that has such people in it."
The separator is: "undefined"
The array has 1 elements: Oh brave new world that has such people in it. / The original string is: "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec"
The separator is: ","
The array has 12 elements: Jan / Feb / Mar / Apr / May / Jun / Jul / Aug / Sep / Oct / Nov / Dec / 示例 2. Consider the following script:

<SCRIPT LANGUAGE="JavaScript1.2">
str="She sells    seashells \nby   the\n seashore"
document.write(str + "<BR>")
a=str.split(" ")
document.write(a)
</SCRIPT>
Using LANGUAGE="JavaScript1.2", this script produces

"She", "sells", "seashells", "by", "the", "seashore" Without LANGUAGE="JavaScript1.2", this script splits only on single space characters, producing

"She", "sells", , , , "seashells", "by", , , "the", "seashore" 示例 3. In the following example, split looks for 0 or more spaces followed by a semicolon followed by 0 or more spaces and, when found, removes the spaces from the string. nameList is the array returned as a result of split.

<SCRIPT>
names = "Harry  Trump  ;Fred Barney; Helen   Rigby ;  Bill Abel ;Chris Hand ";
document.write (names + "<BR>" + "<BR>");
re = /\s*;\s*/;
nameList = names.split (re);
document.write(nameList);
</SCRIPT>
This prints two lines; the first line prints the original string, and the second line prints the resulting array.

Harry Trump ;Fred Barney; Helen Rigby ; Bill Abel ;Chris Hand
Harry Trump,Fred Barney,Helen Rigby,Bill Abel,Chris Hand

示例 4. In the following example, split looks for 0 or more spaces in a string and returns the first 3 splits that it finds.

<SCRIPT LANGUAGE="JavaScript1.2">
myVar = "  Hello World. How are you doing?    ";
splits = myVar.split(" ", 3);
document.write(splits)
</SCRIPT>
This script displays the following:

["Hello", "World.", "How"]

参看

String.charAt, String.indexOf, String.lastIndexOf

strike

Causes a string to be displayed as struck-out text, as if it were in a STRIKE tag.

方法源 | String
实现版本 | Navigator 2.0, LiveWire 1.0

语法

strike()

参数

 无

描述

Use the strike method with the write or writeln methods to format and display a string in a document. In server-side JavaScript, use the write function to display the string.

示例

The following example uses string methods to change the formatting of a string:

var worldString="Hello, world"
document.write(worldString.blink())
document.write("<P>" + worldString.bold())
document.write("<P>" + worldString.italics())
document.write("<P>" + worldString.strike())
The previous example produces the same output as the following HTML:

<BLINK>Hello, world</BLINK>
<P><B>Hello, world</B>
<P><I>Hello, world</I>
<P><STRIKE>Hello, world</STRIKE>

参看

String.blink, String.bold, String.italics

sub

Causes a string to be displayed as a subscript, as if it were in a SUB tag.

方法源 | String
实现版本 | Navigator 2.0, LiveWire 1.0

语法

sub()

参数

 无

描述

Use the sub method with the write or writeln methods to format and display a string in a document. In server-side JavaScript, use the write function to generate the HTML.

示例

The following example uses the sub and sup methods to format a string:

var superText="superscript"
var subText="subscript" document.write("This is what a " + superText.sup() + " looks like.")
document.write("<P>This is what a " + subText.sub() + " looks like.") The previous example produces the same output as the following HTML:

This is what a <SUP>superscript</SUP> looks like.
<P>This is what a <SUB>subscript</SUB> looks like.

参看

String.sup

substr

Returns the characters in a string beginning at the specified location through the specified number of characters.

方法源 | String
实现版本 | Navigator 2.0, LiveWire 1.0

语法

substr(start, length)

参数

start | Location at which to begin extracting characters.
length | (Optional) The number of characters to extract

描述

start is a character index. The index of the first character is 0, and the index of the last character is 1 less than the length of the string. substr begins extracting characters at start and collects length number of characters.

If start is positive and is the length of the string or longer, substr returns no characters.

If start is negative, substr uses it as a character index from the end of the string. If start is negative and abs(start) is larger than the length of the string, substr uses 0 is the start index.

If length is 0 or negative, substr returns no characters. If length is omitted, start extracts characters to the end of the string.

示例

Consider the following script:

<SCRIPT LANGUAGE="JavaScript1.2">
str = "abcdefghij"
document.writeln("(1,2): ", str.substr(1,2))
document.writeln("(-2,2): ", str.substr(-2,2))
document.writeln("(1): ", str.substr(1))
document.writeln("(-20, 2): ", str.substr(1,20))
document.writeln("(20, 2): ", str.substr(20,2))
</SCRIPT>
This script displays:

(1,2): bc
(-2,2): ij
(1): bcdefghij
(-20, 2): bcdefghij
(20, 2):

参看

substring

substring

Returns a subset of a String object.

方法源 | String
实现版本 | Navigator 2.0, LiveWire 1.0

语法

substring(indexA, indexB)

参数

indexA | An integer between 0 and 1 less than the length of the string.
indexB | An integer between 0 and 1 less than the length of the string.

描述

substring extracts characters from indexA up to but not including indexB. In particular:

  • If indexA is less than 0, indexA is treated as if it were 0.

  • If indexB is greater than stringName.length, indexB is treated as if it were stringName.length.

  • If indexA equals indexB, substring returns an empty string.

  • If indexB is omitted, indexA extracts characters to the end of the string.
Using LANGUAGE="JavaScript1.2" in the SCRIPT tag,

  • If indexA is greater than indexB, JavaScript produces a runtime error (out of memory).
Without LANGUAGE="JavaScript1.2",

  • If indexA is greater than indexB, JavaScript returns a substring beginning with indexB and ending with indexA - 1.

示例

 示例 1. The following example uses substring to display characters from the string "Netscape":

var anyString="Netscape"
//Displays "Net"
document.write(anyString.substring(0,3))
document.write(anyString.substring(3,0))
//Displays "cap"
document.write(anyString.substring(4,7))
document.write(anyString.substring(7,4))
//Displays "Netscap"
document.write(anyString.substring(0,7))
//Displays "Netscape"
document.write(anyString.substring(0,8))
document.write(anyString.substring(0,10))
示例 2. The following example replaces a substring within a string. It will replace both individual characters and substrings. The function call at the end of the example changes the string "Brave New World" into "Brave New Web".

function replaceString(oldS,newS,fullS) {
// Replaces oldS with newS in the string fullS
for (var i=0; i<fullS.length; i++) {
if (fullS.substring(i,i+oldS.length) == oldS) {
fullS = fullS.substring(0,i)+newS+fullS.substring(i+oldS.length,fullS.length)
}
}
return fullS
}
replaceString("World","Web","Brave New World")
示例 3. Using LANGUAGE="JavaScript1.2", the following script produces a runtime error (out of memory).

<SCRIPT LANGUAGE="JavaScript1.2">
str="Netscape"
document.write(str.substring(0,3);
document.write(str.substring(3,0);
</SCRIPT>
Without LANGUAGE="JavaScript1.2", the above script prints

Net Net

In the second write, the index numbers are swapped.

参看

substr

sup

Causes a string to be displayed as a superscript, as if it were in a SUP tag.

方法源 | String
实现版本 | Navigator 2.0, LiveWire 1.0

语法

sup()

参数

 无

描述

Use the sup method with the write or writeln methods to format and display a string in a document. In server-side JavaScript, use the write function to generate the HTML.

示例

The following example uses the sub and sup methods to format a string:

var superText="superscript"
var subText="subscript" document.write("This is what a " + superText.sup() + " looks like.")
document.write("<P>This is what a " + subText.sub() + " looks like.") The previous example produces the same output as the following HTML:

This is what a <SUP>superscript</SUP> looks like.
<P>This is what a <SUB>subscript</SUB> looks like.

参看

String.sub

toLowerCase

Returns the calling string value converted to lowercase.

方法源 | String
实现版本 | Navigator 2.0, LiveWire 1.0

语法

toLowerCase()

参数

 无

描述

The toLowerCase method returns the value of the string converted to lowercase. toLowerCase does not affect the value of the string itself.

示例

The following example displays the lowercase string "alphabet":

var upperText="ALPHABET"
document.write(upperText.toLowerCase())

参看

String.toUpperCase

toUpperCase

Returns the calling string value converted to uppercase.

方法源 | String
实现版本 | Navigator 2.0, LiveWire 1.0

语法

toUpperCase()

参数

 无

描述

The toUpperCase method returns the value of the string converted to uppercase. toUpperCase does not affect the value of the string itself.

示例

The following example displays the string "ALPHABET":

var lowerText="alphabet"
document.write(lowerText.toUpperCase())

参看

String.toLowerCase


JavaScript语言参考手册_核心

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

RegExp

 A regular expression object contains the pattern of a regular expression. It has properties and methods for using that regular expression to find and replace matches in strings.

In addition to the properties of an individual regular expression object that you create using the RegExp constructor function, the predefined RegExp object has static properties that are set whenever any regular expression is used.

Core object
实现版本Navigator 4.0, Netscape Server 3.0

创建源

A literal text format or the RegExp constructor function.

The literal format is used as follows:

/pattern/flags The constructor function is used as follows:

new RegExp("pattern", "flags")

参数

patternThe text of the regular expression.
flags(Optional) If specified, flags can have one of the following 3 values:
  • g: global match
  • i: ignore case
  • gi: both global match and ignore case

Notice that the parameters to the literal format do not use quotation marks to indicate strings, while the parameters to the constructor function do use quotation marks. So the following expressions create the same regular expression:

/ab+c/i
new RegExp("ab+c", "i")

描述

When using the constructor function, the normal string escape rules (preceding special characters with \ when included in a string) are necessary. For example, the following are equivalent:

re = new RegExp("\\w+")
re = /\w+/ 表 4.3 provides a complete list and描述 of the special characters that can be used in regular expressions.

表 4.3 Special characters in regular expressions.
Character | Meaning
\ | For characters that are usually treated literally, indicates that the next character is special and not to be interpreted literally. For example, /b/ matches the character 'b'. By placing a backslash in front of b, that is by using /\b/, the character becomes special to mean match a word boundary.-or-For characters that are usually treated specially, indicates that the next character is not special and should be interpreted literally. For example, * is a special character that means 0 or more occurrences of the preceding character should be matched; for example, /a*/ means match 0 or more a's. To match * literally, precede the it with a backslash; for example, /a\*/ matches 'a*'.
^ | Matches beginning of input or line.For example, /^A/ does not match the 'A' in "an A," but does match it in "An A."
$ | Matches end of input or line.For example, /t$/ does not match the 't' in "eater", but does match it in "eat"
* | Matches the preceding character 0 or more times.For example, /bo*/ matches 'boooo' in "A ghost booooed" and 'b' in "A bird warbled", but nothing in "A goat grunted".
+ | Matches the preceding character 1 or more times. Equivalent to {1,}.For example, /a+/ matches the 'a' in "candy" and all the a's in "caaaaaaandy."
? | Matches the preceding character 0 or 1 time.For example, /e?le?/ matches the 'el' in "angel" and the 'le' in "angle."
. | (The decimal point) matches any single character except the newline character.For example, /.n/ matches 'an' and 'on' in "nay, an apple is on the tree", but not 'nay'.
(x) | Matches 'x' and remembers the match.For example, /(foo)/ matches and remembers 'foo' in "foo bar." The matched substring can be recalled from the resulting array's elements [1], ..., [n], or from the predefined RegExp object's properties $1, ..., $9.
x|y | Matches either 'x' or 'y'.For example, /green|red/ matches 'green' in "green apple" and 'red' in "red apple."
{n} | Where n is a positive integer. Matches exactly n occurrences of the preceding character.For example, /a{2}/ doesn't match the 'a' in "candy," but it matches all of the a's in "caandy," and the first two a's in "caaandy."
{n,} | Where n is a positive integer. Matches at least n occurrences of the preceding character.For example, /a{2,} doesn't match the 'a' in "candy", but matches all of the a's in "caandy" and in "caaaaaaandy."
{n,m} | Where n and m are positive integers. Matches at least n and at most m occurrences of the preceding character.For example, /a{1,3}/ matches nothing in "cndy", the 'a' in "candy," the first two a's in "caandy," and the first three a's in "caaaaaaandy" Notice that when matching "caaaaaaandy", the match is "aaa", even though the original string had more a's in it.
[xyz] | A character set. Matches any one of the enclosed characters. You can specify a range of characters by using a hyphen.For example, [abcd] is the same as [a-c]. They match the 'b' in "brisket" and the 'c' in "ache".
[^xyz] | A negated or complemented character set. That is, it matches anything that is not enclosed in the brackets. You can specify a range of characters by using a hyphen.For example, [^abc] is the same as [^a-c]. They initially match 'r' in "brisket" and 'h' in "chop."
[\b] | Matches a backspace. (Not to be confused with \b.)
\b | Matches a word boundary, such as a space. (Not to be confused with [\b].)For example, /\bn\w/ matches the 'no' in "noonday";/\wy\b/ matches the 'ly' in "possibly yesterday."
\B | Matches a non-word boundary.For example, /\w\Bn/ matches 'on' in "noonday", and /y\B\w/ matches 'ye' in "possibly yesterday."
\cX | Where X is a control character. Matches a control character in a string.For example, /\cM/ matches control-M in a string.
\d | Matches a digit character. Equivalent to [0-9].For example, /\d/ or /[0-9]/ matches '2' in "B2 is the suite number."
\D | Matches any non-digit character. Equivalent to [^0-9].For example, /\D/ or /[^0-9]/ matches 'B' in "B2 is the suite number."
\f | Matches a form-feed.
\n | Matches a linefeed.
\r | Matches a carriage return.
\s | Matches a single white space character, including space, tab, form feed, line feed. Equivalent to [ \f\n\r\t\v].for example, /\s\w*/ matches ' bar' in "foo bar."
\S | Matches a single character other than white space. Equivalent to [^ \f\n\r\t\v].For example, /\S/\w* matches 'foo' in "foo bar."
\t | Matches a tab
\v | Matches a vertical tab.
\w | Matches any alphanumeric character including the underscore. Equivalent to [A-Za-z0-9_].For example, /\w/ matches 'a' in "apple," '5' in "$5.28," and '3' in "3D."
\W | Matches any non-word character. Equivalent to [^A-Za-z0-9_].For example, /\W/ or /[^$A-Za-z0-9_]/ matches '%' in "50%."
\n | Where n is a positive integer. A back reference to the last substring matching the n parenthetical in the regular expression (counting left parentheses).For example, /apple(,)\sorange\1/ matches 'apple, orange', in "apple, orange, cherry, peach." A more complete example follows this 表.Note: If the number of left parentheses is less than the number specified in \n, the \n is taken as an octal escape as described in the next row.
\ooctal \xhex | Where \ooctal is an octal escape value or \xhex is a hexadecimal escape value. Allows you to embed ASCII codes into regular expressions.

The literal notation provides compilation of the regular expression when the expression is evaluated. Use literal notation when the regular expression will remain constant. For example, if you use literal notation to construct a regular expression used in a loop, the regular expression won't be recompiled on each iteration.

The constructor of the regular expressionobject, for example, new RegExp("ab+c"), provides runtime compilation of the regular expression. Use the constructor function when you know the regular expression pattern will be changing, or you don't know the pattern and are getting it from another source, such as user input. Once you have a defined regular expression, and if the regular expression is used throughout the script and may change, you can use the compile method to compile a new regular expression for efficient reuse.

A separate predefined RegExp object is available in each window; that is, each separate thread of JavaScript execution gets its own RegExp object. Because each script runs to completion without interruption in a thread, this assures that different scripts do not overwrite values of the RegExp object.

The predefined RegExp object contains the static properties input, multiline, lastMatch, lastParen, leftContext, rightContext, and $1 through $9. The input and multiline properties can be preset. The values for the other static properties are set after execution of the exec and test methods of an individual regular expression object, and after execution of the match and replace methods of String.

属性概览

Note that several of the RegExp properties have both long and short (Perl-like) names. Both names always refer to the same value. Perl is the programming language from which JavaScript modeled its regular expressions.

$1, ..., $9 | Parenthesized substring matches, if any.
$_ | See input.
$* | See multiline.
$& | See lastMatch.
$+ | See lastParen.
$` | See leftContext.
$' | See rightContext.
global | Whether or not to test the regular expression against all possible matches in a string, or only against the first.
ignoreCase | Whether or not to ignore case while attempting a match in a string.
input | The string against which a regular expression is matched.
lastIndex | The index at which to start the next match.
lastMatch | The last matched characters.
lastParen | The last parenthesized substring match, if any.
leftContext | The substring preceding the most recent match.
multiline | Whether or not to search in strings across multiple lines.
rightContext | The substring following the most recent match.
source | The text of the pattern.

方法概览

compile | Compiles a regular expression object.
exec | Executes a search for a match in its string parameter.
test | Tests for a match in its string parameter.

示例

示例 1. The following script uses the replace method to switch the words in the string. For the replacement text, the script uses the values of the $1 and $2 properties of the global RegExp object. Note that the RegExp object name is not be prepended to the $ properties when they are passed as the second argument to the replace method.

<SCRIPT LANGUAGE="JavaScript1.2">
re = /(\w+)\s(\w+)/;
str = "John Smith";
newstr=str.replace(re, "$2, $1");
document.write(newstr)
</SCRIPT>
This displays "Smith, John".

示例 2. In the following example, RegExp.input is set by the Change event. In the getInfo function, the exec method uses the value of RegExp.input as its argument. Note that RegExp is prepended to the $ properties.

<HTML> <SCRIPT LANGUAGE="JavaScript1.2">
function getInfo() {
re = /(\w+)\s(\d+)/;
re.exec();
window.alert(RegExp.$1 + ", your age is " + RegExp.$2);
}
</SCRIPT> Enter your first name and your age, and then press Enter. <FORM>
<INPUT TYPE:"TEXT" NAME="NameAge" onChange="getInfo(this);">
</FORM> </HTML>

属性

$1, ..., $9

 Properties that contain parenthesized substring matches, if any.

属性源 | RegExp
静态, 只读
实现版本 | Navigator 4.0, Netscape Server 3.0

描述

Because input is static, it is not a property of an individual regular expression object. Instead, you always use it as RegExp.input.

The number of possible parenthesized substrings is unlimited, but the predefined RegExp object can only hold the last nine. You can access all parenthesized substrings through the returned array's indexes.

These properties can be used in the replacement text for the String.replace method. When used this way, do not prepend them with RegExp. The example below illustrates this. When parentheses are not included in the regular expression, the script interprets $n's literally (where n is a positive integer).

示例

The following script uses the replace method to switch the words in the string. For the replacement text, the script uses the values of the $1 and $2 properties of the global RegExp object. Note that the RegExp object name is not be prepended to the $ properties when they are passed as the second argument to the replace method.

<SCRIPT LANGUAGE="JavaScript1.2">
re = /(\w+)\s(\w+)/;
str = "John Smith";
newstr=str.replace(re, "$2, $1");
document.write(newstr)
</SCRIPT>
This displays "Smith, John".

$_

See input.

$*

See multiline.

$&

See lastMatch.

$+

See lastParen.

$`

See leftContext.

$'

See rightContext.

global

Whether or not the "g" flag is used with the regular expression.

属性源 | RegExp
只读
实现版本 | Navigator 4.0, Netscape Server 3.0

描述

global is a property of an individual regular expression object.

The value of global is true if the "g" flag was used; otherwise, false. The "g" flag indicates that the regular expression should be tested against all possible matches in a string.

You cannot change this property directly. However, calling the compile method changes the value of this property.

ignoreCase

Whether or not the "i" flag is used with the regular expression.

属性源 | RegExp
只读
实现版本 | Navigator 4.0, Netscape Server 3.0

描述

ignoreCase is a property of an individual regular expression object.

The value of ignoreCase is true if the "i" flag was used; otherwise, false. The "i" flag indicates that case should be ignored while attempting a match in a string.

You cannot change this property directly. However, calling the compile method changes the value of this property.

input

The string against which a regular expression is matched. $_ is another name for the same property.

属性源 | RegExp
静态
实现版本 | Navigator 4.0, Netscape Server 3.0

描述

Because input is static, it is not a property of an individual regular expression object. Instead, you always use it as RegExp.input.

If no string argument is provided to a regular expression's exec or test methods, and if RegExp.input has a value, its value is used as the argument to that method.

The script or the browser can preset the input property. If preset and if no string argument is explicitly provided, the value of input is used as the string argument to the exec or test methods of the regular expression object. input is set by the browser in the following cases:

  • When an event handler is called for a TEXT form element, input is set to the value of the contained text.

  • When an event handler is called for a TEXTAREA form element, input is set to the value of the contained text. Note that multiline is also set to true so that the match can be executed over the multiple lines of text.

  • When an event handler is called for a SELECT form element, input is set to the value of the selected text.

  • When an event handler is called for a Link object, input is set to the value of the text between <A HREF=...> and </A>.
The value of the input property is cleared after the event handler completes.

lastIndex

A read/write integer property that specifies the index at which to start the next match.

属性源 | RegExp
实现版本 | Navigator 4.0, Netscape Server 3.0

描述

lastIndex is a property of an individual regular expression object.

This property is set only if the regular expression used the "g" flag to indicate a global search. The following rules apply:

  • If lastIndex is greater than the length of the string, regexp.test and regexp.exec fail, and lastIndex is set to 0.

  • If lastIndex is equal to the length of the string and if the regular expression matches the empty string, then the regular expression matches input starting at lastIndex.

  • If lastIndex is equal to the length of the string and if the regular expression does not match the empty string, then the regular expression mismatches input, and lastIndex is reset to 0.

  • Otherwise, lastIndex is set to the next position following the most recent match.
For example, consider the following sequence of statements:

re = /(hi)?/g | Matches the empty string.
re("hi") | Returns ["hi", "hi"] with lastIndex equal to 2.
re("hi") | Returns [""], an empty array whose zeroth element is the match string. In this case, the empty string because lastIndex was 2 (and still is 2) and "hi" has length 2.

lastMatch

The last matched characters. $& is another name for the same property.

属性源 | RegExp
静态, 只读
实现版本 | Navigator 4.0, Netscape Server 3.0

描述

Because lastMatch is static, it is not a property of an individual regular expression object. Instead, you always use it as RegExp.lastMatch.

lastParen

The last parenthesized substring match, if any. $+ is another name for the same property.

属性源 | RegExp
静态, 只读
实现版本 | Navigator 4.0, Netscape Server 3.0

描述

Because lastParen is static, it is not a property of an individual regular expression object. Instead, you always use it as RegExp.lastParen.

leftContext

The substring preceding the most recent match. $` is another name for the same property.

属性源 | RegExp
静态, 只读
实现版本 | Navigator 4.0, Netscape Server 3.0

描述

Because leftContext is static, it is not a property of an individual regular expression object. Instead, you always use it as RegExp.leftContext.

multiline

Reflects whether or not to search in strings across multiple lines. $* is another name for the same property.

属性源 | RegExp
静态
实现版本 | Navigator 4.0, Netscape Server 3.0

描述

Because multiline is static, it is not a property of an individual regular expression object. Instead, you always use it as RegExp.multiline.

The value of multiline is true if multiple lines are searched, false if searches must stop at line breaks.

The script or the browser can preset the multiline property. When an event handler is called for a TEXTAREA form element, the browser sets multiline to true. multiline is cleared after the event handler completes. This means that, if you've preset multiline to true, it is reset to false after the execution of any event handler.

rightContext

The substring following the most recent match. $' is another name for the same property.

属性源 | RegExp
静态, 只读
实现版本 | Navigator 4.0, Netscape Server 3.0

描述

Because rightContext is static, it is not a property of an individual regular expression object. Instead, you always use it as RegExp.rightContext.

source

A read-only property that contains the text of the pattern, excluding the forward slashes and "g" or "i" flags.

属性源 | RegExp
只读
实现版本 | Navigator 4.0, Netscape Server 3.0

描述

source is a property of an individual regular expression object.

You cannot change this property directly. However, calling the compile method changes the value of this property.

方法

compile

 Compiles a regular expression object during execution of a script.

方法源 | RegExp
实现版本 | Navigator 4.0, Netscape Server 3.0

语法

regexp.compile(pattern, flags)

参数

regexpThe name of the regular expression. It can be a variable name or a literal.
patternA string containing the text of the regular expression.
flags(Optional) If specified, flags can have one of the following 3 values:
  • "g": global match
  • "i": ignore case
  • "gi": both global match and ignore case

描述

Use the compile method to compile a regular expression created with the RegExp constructor function. This forces compilation of the regular expression once only which means the regular expression isn't compiled each time it is encountered. Use the compile method when you know the regular expression will remain constant (after getting its pattern) and will be used repeatedly throughout the script.

You can also use the compile method to change the regular expression during execution. For example, if the regular expression changes, you can use the compile method to recompile the object for more efficient repeated use.

Calling this method changes the value of the regular expression's source, global, and ignoreCase properties.

exec

Executes the search for a match in a specified string. Returns a result array.

方法源 | RegExp
实现版本 | Navigator 4.0, Netscape Server 3.0

语法

regexp.exec(str)
regexp(str)

参数

regexp | The name of the regular expression. It can be a variable name or a literal.
str | (Optional) The string against which to match the regular expression. If omitted, the value of RegExp.input is used.

描述

As shown in the语法描述, a regular expression's exec method call be called either directly, (with regexp.exec(str)) or indirectly (with regexp(str)).

If you are executing a match simply to find true or false, use the test method or the String search method.

If the match succeeds, the exec method returns an array and updates properties of the regular expression object and the predefined regular expression object, RegExp. If the match fails, the exec method returns null.

Consider the following example:

<SCRIPT LANGUAGE="JavaScript1.2">
//Match one d followed by one or more b's followed by one d
//Remember matched b's and the following d
//Ignore case
myRe=/d(b+)(d)/ig;
myArray = myRe.exec("cdbBdbsbz");
</SCRIPT>
The following 表 shows the results for this script:

对象 | Property/Index | 描述 | Example
myArray |  | The contents of myArray | ["dbBd", "bB", "d"]
 | index | The 0-based index of the match in the string | 1
 | input | The original string | cdbBdbsbz
 | [0] | The last matched characters | dbBd
 | [1], ...[n] | The parenthesized substring matches, if any. The number of possible parenthesized substrings is unlimited. | [1] = bB [2] = d
myRe | lastIndex | The index at which to start the next match. | 5
 | ignoreCase | Indicates if the "i" flag was used to ignore case | true
 | global | Indicates if the "g" flag was used for a global match | true
 | source | The text of the pattern | d(b+)(d)
RegExp | lastMatch $& | The last matched characters | dbBd
 | leftContext $\Q | The substring preceding the most recent match | c
 | rightContext $' | The substring following the most recent match | bsbz
 | $1, ...$9 | The parenthesized substring matches, if any. The number of possible parenthesized substrings is unlimited, but RegExp can only hold the last nine. | $1 = bB $2 = d
 | lastParen $+ | The last parenthesized substring match, if any. | d

If your regular expression uses the "g" flag, you can use the exec method multiple times to find successive matches in the same string. When you do so, the search starts at the substring of str specified by the regular expression's lastIndex property. For example, assume you have this script:

<SCRIPT LANGUAGE="JavaScript1.2">
myRe=/ab*/g;
str = "abbcdefabh"
myArray = myRe.exec(str);
document.writeln("Found " + myArray[0] +
". Next match starts at " + myRe.lastIndex)
mySecondArray = myRe.exec(str);
document.writeln("Found " + mySecondArray[0] +
". Next match starts at " + myRe.lastIndex)
</SCRIPT> This script displays the following text:

Found abb. Next match starts at 3
Found ab. Next match starts at 9

示例

In the following example, the user enters a name and the script executes a match against the input. It then cycles through the array to see if other names match the user's name.

This script assumes that first names of registered party attendees are preloaded into the array A, perhaps by gathering them from a party database.

<HTML>
<SCRIPT LANGUAGE="JavaScript1.2">
A = ["Frank", "Emily", "Jane", "Harry", "Nick", "Beth", "Rick",
"Terrence", "Carol", "Ann", "Terry", "Frank", "Alice", "Rick",
"Bill", "Tom", "Fiona", "Jane", "William", "Joan", "Beth"]
function lookup() {
firstName = /\w+/i();
if (!firstName)
window.alert (RegExp.input + " isn't a name!");
else {
count = 0;
for (i=0; i<A.length; i++)
if (firstName[0].toLowerCase() == A[i].toLowerCase()) count++;
if (count ==1)
midstring = " other has ";
else
midstring = " others have ";
window.alert ("Thanks, " + count + midstring + "the same name!")
}
}
</SCRIPT>
Enter your first name and then press Enter.
<FORM> <INPUT TYPE:"TEXT" NAME="FirstName" onChange="lookup(this);"> </FORM>
</HTML>

test

Executes the search for a match between a regular expression and a specified string. Returns true or false.

方法源 | RegExp
实现版本 | Navigator 4.0, Netscape Server 3.0

语法

regexp.test(str)

参数

regexp | The name of the regular expression. It can be a variable name or a literal.
str | (Optional) The string against which to match the regular expression. If omitted, the value of RegExp.input is used.

描述

When you want to know whether a pattern is found in a string use the test method (similar to the String.search method); for more information (but slower execution) use the exec method (similar to the String.match method).

示例

The following example prints a message which depends on the success of the test:

function testinput(re, str){
if (re.test(str))
midstring = " contains ";
else
midstring = " does not contain ";
document.write (str + midstring + re.source);
}

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


JavaScript语言参考手册_文档

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

第五章
文档

本章描述了文档及其关联对象 document、Layer、Link、Anchor、Area、Image 和 Applet。

表 5.1 本章用到的对象总览。

表 5.1 文档对象
对象 | 描述
Anchor | 超文本链接指向文档某处的目的地。
Applet | 在 Web 页上包含 Java 小应用程序。
Area | 将图像的一个区域定义为图像映射。
document | 包含了当前文档的信息，并提供了向用户显示 HTML 输出的方法。
Image | HTML 表单中的一个图像。
Layer | 对应一个 HTML 页中的层，并提供了操纵该层的一种手段。
Link | 被申明为超文本链接的一片文本、一个图像或者图像的一个区域。

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


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.

  • onClick
  • onDblClick
  • onKeyDown
  • onKeyPress
  • onKeyUp
  • onMouseDown
  • onMouseUp

描述

 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.

属性概览

alinkColor | A string that specifies the ALINK attribute.
anchors | An array containing an entry for each anchor in the document.
applets | An array containing an entry for each applet in the document.
bgColor | A string that specifies the BGCOLOR attribute.
cookie | Specifies a cookie.
domain | Specifies the domain name of the server that served a document.
embeds | An array containing an entry for each plug-in in the document.
fgColor | A string that specifies the TEXT attribute.
formName | A separate 属性 for each named form in the document.
forms | An array a containing an entry for each form in the document.
images | An array containing an entry for each image in the document.
lastModified | A string that specifies the date the document was last modified.
layers | Array containing an entry for each layer within the document.
linkColor | A string that specifies the LINK attribute.
links | An array containing an entry for each link in the document.
plugins | An array containing an entry for each plug-in in the document.
referrer | A string that specifies the URL of the calling document.
title | A string that specifies the contents of the TITLE tag.
URL | A string that specifies the complete URL of a document.
vlinkColor | A string that specifies the VLINK attribute.

方法概览

captureEvents | Sets the document to capture all events of the specified type.
close | Closes an output stream and forces data to display.
getSelection | Returns a string containing the text of the current selection.
handleEvent | 调用指定事件的控制句柄。
open | Opens a stream to collect the output of write or writeln 方法s.
releaseEvents | Sets the window or document to release captured events of thespecified type, sending the event to objects further along the event hierarchy.
routeEvent | Passes a captured event along the normal event hierarchy.
write | Writes one or more HTML expressions to a document in the specified window.
writeln | Writes 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:

  • Wdy is a string representing the full name of the day of the week.

  • DD is an integer representing the day of the month.

  • Mon is a string representing the three-character abbreviation of the month.

  • YY is an integer representing the last two digits of the year.

  • HH, MM, and SS are 2-digit representations of hours, minutes, and seconds, respectively.
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:

  • Dashes are added between the day, month, and year.

  • The year is a 2-digit value for cookies.

示例

 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:

  • Setting the COLOR attribute of the FONT tag.

  • Using the fontcolor method.

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:

  • text/html specifies a document containing ASCII text with HTML formatting.

  • text/plain specifies a document containing plain ASCII text with end-of-line characters to delimit displayed lines.

  • image/gif specifies a document with encoded bytes constituting a GIF header and pixel data.

  • image/jpeg specifies a document with encoded bytes constituting a JPEG header and pixel data.

  • image/x-bitmap specifies a document with encoded bytes constituting a bitmap header and pixel data.

  • plugIn loads the specified plug-in and uses it as the destination for write and writeln methods. For example, "x-world/vrml" loads the VR Scout VRML plug-in from Chaco Communications, and "application/x-director" loads the Macromedia Shockwave plug-in. Plug-in MIME types are only valid if the user has installed the required plug-in software.
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


JavaScript语言参考手册_文档

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

Link

 A piece of text, an image, or an area of an image identified as a hypertext link. When the user clicks the link text, image, or area, the link hypertext reference is loaded into its target window. Area objects are a type of Link object.

客户端对象
实现版本Navigator 2.0
Navigator 3.0: 添加了 onMouseOut event handler; 添加了 Area objects; links array contains areas created with <AREA HREF="...">
Navigator 4.0: 添加了 handleEvent 方法

创建源

By using the HTML A or AREA tag or by a call to the String.link method. The JavaScript runtime engine creates a Link object corresponding to each A and AREA tag in your document that supplies the HREF attribute. It puts these objects as an array in the document.links property. You access a Link object by indexing this array.

To define a link with the String.link method:

theString.link(hrefAttribute) where:

theString | A String object.
hrefAttribute | Any string that specifies the HREF attribute of the A tag; it should be a valid URL (relative or absolute).

To define a link with the A or MAP tag, use standard HTML语法 with the addition of JavaScript event handlers. If you're going to use the onMouseOut or onMouseOver event handlers, you must supply a value for the HREF attribute.

事件句柄

Area objects have the following event handlers:

  • onDblClick
  • onMouseOut
  • onMouseOver
Link objects have the following event handlers:

  • onClick
  • onDblClick
  • onKeyDown
  • onKeyPress
  • onKeyUp
  • onMouseDown
  • onMouseOut
  • onMouseUp
  • onMouseOver

描述

 Each Link object is a location object and has the same properties as a location object.

If a Link object is also an Anchor object, the object has entries in both the anchors and links arrays.

When a user clicks a Link object and navigates to the destination document (specified by HREF="locationOrURL"), the destination document's referrer property contains the URL of the source document. Evaluate the referrer property from the destination document.

You can use a Link object to execute a JavaScript function rather than link to a hypertext reference by specifying the javascript: URL protocol for the link's HREF attribute. You might want to do this if the link surrounds an Image object and you want to execute JavaScript code when the image is clicked. Or you might want to use a link instead of a button to execute JavaScript code.

For example, when a user clicks the following links, the slower and faster functions execute:

<A HREF="javascript:slower()">Slower</A>
<A HREF="javascript:faster()">Faster</A> You can use a Link object to do nothing rather than link to a hypertext reference by specifying the javascript:void(0) URL protocol for the link's HREF attribute. You might want to do this if the link surrounds an Image object and you want to use the link's event handlers with the image. When a user clicks the following link or image, nothing happens:

<A HREF="javascript:void(0)">Click here to do nothing</A>
<A HREF="javascript:void(0)">
<IMG SRC="images\globe.gif" ALIGN="top" HEIGHT="50" WIDTH="50">
</A>

属性概览

hash | Specifies an anchor name in the URL.
host | Specifies the host and domain name, or IP address, of a network host.
hostname | Specifies the host:port portion of the URL.
href | Specifies the entire URL.
pathname | Specifies the URL-path portion of the URL.
port | Specifies the communications port that the server uses.
protocol | Specifies the beginning of the URL, including the colon.
search | Specifies a query string.
target | Reflects the TARGET attribute.
text | A string containing the content of the corresponding A tag.

方法概览

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

示例

示例 1. The following example creates a hypertext link to an anchor named javascript_intro:

<A HREF="#javascript_intro">Introduction to JavaScript</A> 示例 2. The following example creates a hypertext link to an anchor named numbers in the file doc3.html in the window window2. If window2 does not exist, it is created.

<LI><A HREF=doc3.html#numbers TARGET="window2">Numbers</A> 示例 3. The following example takes the user back x entries in the history list:

<A HREF="javascript:history.go(-1 * x)">Click here</A> 示例 4. The following example creates a hypertext link to a URL. The user can use the set of radio buttons to choose between three URLs. The link's onClick event handler sets the URL (the link's href property) based on the selected radio button. The link also has an onMouseOver event handler that changes the window's status property. As the example shows, you must return true to set the window.status property in the onMouseOver event handler.

<SCRIPT>
var destHREF="http://home.netscape.com/"
</SCRIPT>
<FORM NAME="form1">
<B>Choose a destination from the following list, then click "Click me" below.</B>
<BR><INPUT TYPE="radio" NAME="destination" VALUE="netscape"
onClick="destHREF='http://home.netscape.com/'"> Netscape home page
<BR><INPUT TYPE="radio" NAME="destination" VALUE="sun"
onClick="destHREF='http://www.sun.com/'"> Sun home page
<BR><INPUT TYPE="radio" NAME="destination" VALUE="rfc1867"
onClick="destHREF='http://www.ics.uci.edu/pub/ietf/html/rfc1867.txt'"> RFC 1867
<P><A HREF=""
onMouseOver="window.status='Click this if you dare!'; return true"
onClick="this.href=destHREF">
<B>Click me</B></A>
</FORM>
示例 5: links array. In the following example, the linkGetter function uses the links array to display the value of each link in the current document. The example also defines several links and a button for running linkGetter.

function linkGetter() {
msgWindow=window.open("","msg","width=400,height=400")
msgWindow.document.write("links.length is " +
document.links.length + "<BR>")
for (var i = 0; i < document.links.length; i++) {
msgWindow.document.write(document.links[i] + "<BR>")
}
}
<A HREF="http://home.netscape.com">Netscape Home Page</A>
<A HREF="http://www.catalog.com/fwcfc/">China Adoptions</A>
<A HREF="http://www.supernet.net/~dugbrown/">Bad Dog Chronicles</A>
<A HREF="http://www.best.com/~doghouse/homecnt.shtml">Lab Rescue</A>
<P>
<INPUT TYPE="button" VALUE="Display links"
onClick="linkGetter()">
示例 6: Refer to Area object with links array. The following code refers to the href property of the first Area object shown in Example 1.

document.links[0].href 示例 7: Area object with onMouseOver and onMouseOut event handlers. The following example displays an image, globe.gif. The image uses an image map that defines areas for the top half and the bottom half of the image. The onMouseOver and onMouseOut event handlers display different status bar messages depending on whether the mouse passes over or leaves the top half or bottom half of the image. The HREF attribute is required when using the onMouseOver and onMouseOut event handlers, but in this example the image does not need a hypertext link, so the HREF attribute executes javascript:void(0), which does nothing.

<MAP NAME="worldMap">
<AREA NAME="topWorld" COORDS="0,0,50,25" HREF="javascript:void(0)"
onMouseOver="self.status='You are on top of the world';return true"
onMouseOut="self.status='You have left the top of the world';return true">
<AREA NAME="bottomWorld" COORDS="0,25,50,50" HREF="javascript:void(0)"
onMouseOver="self.status='You are on the bottom of the world';return true"
onMouseOut="self.status='You have left the bottom of the world';return true">
</MAP>
<IMG SRC="images\globe.gif" ALIGN="top" HEIGHT="50" WIDTH="50" USEMAP="#worldMap">
示例 8: Simulate an Area object's onClick using the HREF attribute. The following example uses an Area object's HREF attribute to execute a JavaScript function. The image displayed, colors.gif, shows two sample colors. The top half of the image is the color antiquewhite, and the bottom half is white. When the user clicks the top or bottom half of the image, the function setBGColor changes the document's background color to the color shown in the image.

<SCRIPT>
function setBGColor(theColor) {
document.bgColor=theColor
}
</SCRIPT>
Click the color you want for this document's background color
<MAP NAME="colorMap">
<AREA NAME="topColor" COORDS="0,0,50,25" HREF="javascript:setBGColor('antiquewhite')">
<AREA NAME="bottomColor" COORDS="0,25,50,50" HREF="javascript:setBGColor('white')">
</MAP>
<IMG SRC="images\colors.gif" ALIGN="top" HEIGHT="50" WIDTH="50" USEMAP="#colorMap">

参看

Anchor, Image, link

属性

hash

 A string beginning with a hash mark (#) that specifies an anchor name in the URL.

属性源 | Link
实现版本 | Navigator 2.0

安全性

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

描述

The hash property specifies a portion of the URL. This property applies to HTTP URLs only.

Be careful using this property. Assume document.links[0] contains:

http://royalairways.com/fish.htm#angel Then document.links[0].hash returns #angel. Assume you have this code:

hash = document.links[0].hash;
document.links[0].hash = hash; Now, document.links[0].hash returns ##angel.

This behavior may change in a future release.

You can set the hash property at any time, although it is safer to set the href property to change a location. If the hash that you specify cannot be found in the current location, you get an error.

Setting the hash property navigates to the named anchor without reloading the document. This differs from the way a document is loaded when other link properties are set.

See RFC 1738 (http://www.cis.ohio-state.edu/htbin/rfc/rfc1738.html) for complete information about the hash.

参看

Link.host, Link.hostname, Link.href, Link.pathname, Link.port, Link.protocol, Link.search

host

A string specifying the server name, subdomain, and domain name.

属性源 | Link
实现版本 | Navigator 2.0

安全性

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

描述

The host property specifies a portion of a URL. The host property is a substring of the hostname property. The hostname property is the concatenation of the host and port properties, separated by a colon. When the port property is null, the host property is the same as the hostname property.

You can set the host property at any time, although it is safer to set the href property to change a location. If the host that you specify cannot be found in the current location, you get an error.

See Section 3.1 of RFC 1738 (http://www.cis.ohio-state.edu/htbin/rfc/rfc1738.html) for complete information about the hostname and port.

参看

Link.hash, Link.hostname, Link.href, Link.pathname, Link.port, Link.protocol, Link.search

hostname

A string containing the full hostname of the server, including the server name, subdomain, domain, and port number.

属性源 | Link
实现版本 | Navigator 2.0

安全性

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

描述

The hostname property specifies a portion of a URL. The hostname property is the concatenation of the host and port properties, separated by a colon. When the port property is 80 (the default), the host property is the same as the hostname property.

You can set the hostname property at any time, although it is safer to set the href property to change a location. If the hostname that you specify cannot be found in the current location, you get an error.

See Section 3.1 of RFC 1738 (http://www.cis.ohio-state.edu/htbin/rfc/rfc1738.html) for complete information about the hostname.

参看

Link.host, Link.hash, Link.href, Link.pathname, Link.port, Link.protocol, Link.search

href

A string specifying the entire URL.

属性源 | Link
实现版本 | Navigator 2.0

安全性

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

描述

The href property specifies the entire URL. Other link object properties are substrings of the href property.

You can set the href property at any time.

See RFC 1738 (http://www.cis.ohio-state.edu/htbin/rfc/rfc1738.html) for complete information about the URL.

参看

Link.hash, Link.host, Link.hostname, Link.pathname, Link.port, Link.protocol, Link.search

pathname

A string specifying the URL-path portion of the URL.

属性源 | Link
实现版本 | Navigator 2.0

安全性

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

描述

The pathname property specifies a portion of the URL. The pathname supplies the details of how the specified resource can be accessed.

You can set the pathname property at any time, although it is safer to set the href property to change a location. If the pathname that you specify cannot be found in the current location, you get an error.

See Section 3.1 of RFC 1738 (http://www.cis.ohio-state.edu/htbin/rfc/rfc1738.html) for complete information about the pathname.

参看

Link.host, Link.hostname, Link.hash, Link.href, Link.port, Link.protocol, Link.search

port

A string specifying the communications port that the server uses.

属性源 | Link
实现版本 | Navigator 2.0

安全性

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

描述

The port property specifies a portion of the URL. The port property is a substring of the hostname property. The hostname property is the concatenation of the host and port properties, separated by a colon. When the port property is 80 (the default), the host property is the same as the hostname property.

You can set the port property at any time, although it is safer to set the href property to change a location. If the port that you specify cannot be found in the current location, you will get an error. If the port property is not specified, it defaults to 80 on the server.

See Section 3.1 of RFC 1738 (http://www.cis.ohio-state.edu/htbin/rfc/rfc1738.html) for complete information about the port.

参看

Link.host, Link.hostname, Link.hash, Link.href, Link.pathname, Link.protocol, Link.search

protocol

A string specifying the beginning of the URL, up to and including the first colon.

属性源 | Link
实现版本 | Navigator 2.0

安全性

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

描述

The protocol property specifies a portion of the URL. The protocol indicates the access method of the URL. For example, the value "http:" specifies HyperText Transfer Protocol, and the value "javascript:" specifies JavaScript code.

You can set the protocol property at any time, although it is safer to set the href property to change a location. If the protocol that you specify cannot be found in the current location, you get an error.

The protocol property represents the scheme name of the URL. See Section 2.1 of RFC 1738 (http://www.cis.ohio-state.edu/htbin/rfc/rfc1738.html) for complete information about the protocol.

参看

Link.host, Link.hostname, Link.hash, Link.href, Link.pathname, Link.port, Link.search

search

A string beginning with a question mark that specifies any query information in the URL.

属性源 | Link
实现版本 | Navigator 2.0

安全性

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

描述

The search property specifies a portion of the URL. This property applies to http URLs only.

The search property contains variable and value pairs; each pair is separated by an ampersand. For example, two pairs in a search string could look like the following:

?x=7&y=5 You can set the search property at any time, although it is safer to set the href property to change a location. If the search that you specify cannot be found in the current location, you get an error.

See Section 3.3 of RFC 1738 (http://www.cis.ohio-state.edu/htbin/rfc/rfc1738.html) for complete information about the search.

参看

Link.host, Link.hostname, Link.hash, Link.href, Link.pathname, Link.port, Link.protocol

target

A string specifying the name of the window that displays the content of a clicked hypertext link.

属性源 | Link
实现版本 | Navigator 2.0

描述

The target property initially reflects the TARGET attribute of the A or AREA tags; however, setting target overrides this attribute.

You can set target using a string, if the string represents a window name. The target property cannot be assigned the value of a JavaScript expression or variable.

You can set the target property at any time.

示例

The following example specifies that responses to the musicInfo form are displayed in the msgWindow window:

document.musicInfo.target="msgWindow"

参看

Form

text

A string containing the content of the corresponding A tag.

属性源 | Link
实现版本 | Navigator 4.0

方法

handleEvent

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

方法源 | Link
实现版本 | Navigator 4.0

语法

handleEvent(event)

参数

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

描述

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


JavaScript语言参考手册_文档

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

Area

 将一幅图像的一部分定义为一个图像地图。当用户单击该区域时，将在区域的目的窗口中装载其超链接指向的引用。Area 对象是 Link 对象的一种类型。

客户端对象 |
实现版本 | Navigator 3.0:

要获取关于 Area 对象更多的信息，请参看 Link 。


JavaScript语言参考手册_文档

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

Anchor

 文档中超级链接的目的地，称为锚。

客户端对象 |
实现版本 | Navigator 2.0

创建源

使用 HTML A 标签或调用 String.anchor 方法。JavaScript 运行时刻引擎将为文档中的每个含有 NAME 属性的 A 标签创建一个对应的 Anchor 对象。它会将这些对象放在 document.anchors 属性数组中。你可以通过该数组的索引来访问一个 Anchor 对象。

要使用 String.anchor 方法定义一个锚，可用下面的格式：

theString.anchor(nameAttribute)
这里：

theString | 一个 String 对象。
nameAttribute | 一个字符串。

要使用 A 标签定义锚，应该使用标准的 HTML 语法。如果你指定了 NAME 属性，你就可以使用该属性值作为索引在 anchors 数组中找到该 Anchor 对象。

描述

如果一个 Anchor 对象还是一个 Link 对象的话，该对象就会同时存在于 anchors 和 links 数组。

属性

无。

方法

无。

示例

示例 1: 一个锚。下面的例子为文本“欢迎来到 JavaScript”定义了一个锚：

<A NAME="javascript_intro"><H2>欢迎来到 JavaScript</H2></A>
 如果上面的锚是在叫做 intro.html 的文件中定义的话，其它文件就可以用下面的方法定义到该锚的跳转：

<A HREF="intro.html#javascript_intro">简介</A>

示例 2: anchors 数组。下面的例子将打开两个窗口。第一个窗口包含了一系列按钮，可将第二个窗口的 location.hash 设定为指定的锚。第二个窗口定义了四个锚，分别叫做“0”、“1”、“2”和“3”。(因此，锚的名称就依次为 0、1、2、……(document.anchors.length-1)。)如果用户按了第一个窗口的按钮，onClick 事件句柄就会在设置 window2.locatin.hash 为指定锚名称之前检验锚的存在与否。

link1.html，定义了第一个窗口及其按钮，包含了下列代码：

<HTML>
<HEAD>
<TITLE>链接和锚：窗口 1</TITLE>
</HEAD>
<BODY>
<SCRIPT>
window2=open("link2.html","secondLinkWindow",
"scrollbars=yes,width=250, height=400")
function linkToWindow(num) {
if (window2.document.anchors.length > num)
window2.location.hash=num
else
alert("锚不存在！")
}
</SCRIPT>
<B>链接和锚</B>
<FORM>
<P>单击一个按钮可以在窗口 2 中显示对应的锚
<P><INPUT TYPE="button" VALUE="0" NAME="link0_button"
onClick="linkToWindow(this.value)">
<INPUT TYPE="button" VALUE="1" NAME="link0_button"
onClick="linkToWindow(this.value)">
<INPUT TYPE="button" VALUE="2" NAME="link0_button"
onClick="linkToWindow(this.value)">
<INPUT TYPE="button" VALUE="3" NAME="link0_button"
onClick="linkToWindow(this.value)">
<INPUT TYPE="button" VALUE="4" NAME="link0_button"
onClick="linkToWindow(this.value)">
</FORM>
</BODY>
</HTML>

link2.html，包含了锚，以及下列代码：

<HTML>
<HEAD>
<TITLE>链接和锚，窗口 2</TITLE>
</HEAD>
<BODY>
<A NAME="0"><B>一些数字</B> (锚 0)</A>
<UL><LI>一
<LI>二
<LI>三
<LI>四</UL>
<P><A NAME="1"><B>一些颜色</B> (锚 1)</A>
<UL><LI>红
<LI>橙
<LI>黄
<LI>绿</UL>
<P><A NAME="2"><B>一些音乐风格</B> (锚 2)</A>
<UL><LI>布鲁斯
<LI>爵士
<LI>摇滚
<LI>交响
<LI>民谣</UL>
<P><A NAME="3"><B>一些国家</B> (锚 3)</A>
<UL><LI>中国
<LI>美国
<LI>加拿大
<LI>日本
<LI>印度</UL>
</BODY>
</HTML>

参看

Link


JavaScript语言参考手册_文档

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

Image

An image on an HTML form.

客户端对象 |
实现版本 | Navigator 3.0 Navigator 4.0: 添加了 handleEvent 方法

创建源

The Image constructor or the IMG tag.

The JavaScript runtime engine creates an Image object corresponding to each IMG tag in your document. It puts these objects in an array in the document.images property. You access an Image object by indexing this array.

To define an image with the IMG tag, use standard HTML语法 with the addition of JavaScript event handlers. If specify a value for the NAME attribute, you can use that name when indexing the images array.

To define an image with its constructor, use the following语法:

new Image(width, height)

参数

width | (Optional) The image width, in pixels.
height | (Optional) The image height, in pixels.

事件句柄

  • onAbort
  • onError
  • onKeyDown
  • onKeyPress
  • onKeyUp
  • onLoad
To define an事件适用对象an Image object created with the Image constructor, set the appropriate property of the object. For example, if you have an Image object named imageName and you want to set one of its event handlers to a function whose name is handlerFunction, use one of the following statements:

imageName.onabort = handlerFunction
imageName.onerror = handlerFunction
imageName.onkeydown = handlerFunction
imageName.onkeypress = handlerFunction
imageName.onkeyup = handlerFunction
imageName.onload = handlerFunction
Image objects do not have onClick, onMouseOut, and onMouseOver event handlers. However, if you define an Area object for the image or place the IMG tag within a Link object, you can use the Area or Link object's event handlers. See Link.

描述

The position and size of an image in a document are set when the document is displayed in the web browser and cannot be changed using JavaScript (the width and height properties are read-only for these objects). You can change which image is displayed by setting the src and lowsrc properties. (See the描述s of Image.src and Image.lowsrc.)

You can use JavaScript to create an animation with an Image object by repeatedly setting the src property, as shown in Example 4 below. JavaScript animation is slower than GIF animation, because with GIF animation the entire animation is in one file; with JavaScript animation, each frame is in a separate file, and each file must be loaded across the network (host contacted and data transferred).

The primary use for an Image object created with the Image constructor is to load an image from the network (and decode it) before it is actually needed for display. Then when you need to display the image within an existing image cell, you can set the src property of the displayed image to the same value as that used for the previously fetched image, as follows.

myImage = new Image()
myImage.src = "seaotter.gif"
...
document.images[0].src = myImage.src The resulting image will be obtained from cache, rather than loaded over the network, assuming that sufficient time has elapsed to load and decode the entire image. You can use this technique to create smooth animations, or you could display one of several images based on form input.

属性概览

border | Reflects the BORDER attribute.
complete | Boolean value indicating whether the web browser has completed its attempt to load the image.
height | Reflects the HEIGHT attribute.
hspace | Reflects the HSPACE attribute.
lowsrc | Reflects the LOWSRC attribute.
name | Reflects the NAME attribute.
prototype | Allows the addition of properties to an Image object.
src | Reflects the SRC attribute.
vspace | Reflects the VSPACE attribute.
width | Reflects the WIDTH attribute.

方法概览

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

示例

示例 1: Create an image with the IMG tag. The following code defines an image using the IMG tag:

<IMG NAME="aircraft" SRC="f15e.gif" ALIGN="left" VSPACE="10"> The following code refers to the image:

document.aircraft.src='f15e.gif' When you refer to an image by its name, you must include the form name if the image is on a form. The following code refers to the image if it is on a form:

document.myForm.aircraft.src='f15e.gif' 示例 2: Create an image with the Image constructor. The following example creates an Image object, myImage, that is 70 pixels wide and 50 pixels high. If the source URL, seaotter.gif, does not have dimensions of 70x50 pixels, it is scaled to that size.

myImage = new Image(70, 50)
myImage.src = "seaotter.gif" If you omit the width and height arguments from the Image constructor, myImage is created with dimensions equal to that of the image named in the source URL.

myImage = new Image()
myImage.src = "seaotter.gif" 示例 3: Display an image based on form input. In the following example, the user selects which image is displayed. The user orders a shirt by filling out a form. The image displayed depends on the shirt color and size that the user chooses. All possible image choices are preloaded to speed response time. When the user clicks the button to order the shirt, the allShirts function displays the images of all the shirts.

<SCRIPT>
shirts = new Array()
shirts[0] = "R-S"
shirts[1] = "R-M"
shirts[2] = "R-L"
shirts[3] = "W-S"
shirts[4] = "W-M"
shirts[5] = "W-L"
shirts[6] = "B-S"
shirts[7] = "B-M"
shirts[8] = "B-L" doneThis = 0
shirtImg = new Array() // Preload shirt images
for(idx=0; idx < 9; idx++) {
shirtImg[idx] = new Image()
shirtImg[idx].src = "shirt-" + shirts[idx] + ".gif"
} function changeShirt(form)
{
shirtColor = form.color.options[form.color.selectedIndex].text
shirtSize = form.size.options[form.size.selectedIndex].text newSrc = "shirt-" + shirtColor.charAt(0) + "-" + shirtSize.charAt(0) + ".gif"
document.shirt.src = newSrc
} function allShirts()
{
document.shirt.src = shirtImg[doneThis].src
doneThis++
if(doneThis != 9)setTimeout("allShirts()", 500)
else doneThis = 0 return
} </SCRIPT> <FONT SIZE=+2><B>Netscape Polo Shirts!</FONT></B> <表 CELLSPACING=20 BORDER=0>
<TR>
<TD><IMG name="shirt" SRC="shirt-W-L.gif"></TD> <TD>
<FORM>
<B>Color</B>
<SELECT SIZE=3 NAME="color" onChange="changeShirt(this.form)">
<OPTION> Red
<OPTION SELECTED> White
<OPTION> Blue
</SELECT> <P>
<B>Size</B>
<SELECT SIZE=3 NAME="size" onChange="changeShirt(this.form)">
<OPTION> Small
<OPTION> Medium
<OPTION SELECTED> Large
</SELECT> <P><INPUT type="button" name="buy" value="Buy This Shirt!"
onClick="allShirts()">
</FORM> </TD>
</TR>
</表> 示例 4: JavaScript animation. The following example uses JavaScript to create an animation with an Image object by repeatedly changing the value the src property. The script begins by preloading the 10 images that make up the animation (image1.gif, image2.gif, image3.gif, and so on). When the Image object is placed on the document with the IMG tag, image1.gif is displayed and the onLoad event handler starts the animation by calling the animate function. Notice that the animate function does not call itself after changing the src property of the Image object. This is because when the src property changes, the image's onLoad event handler is triggered and the animate function is called.

<SCRIPT>
delay = 100
imageNum = 1
// Preload animation images
theImages = new Array()
for(i = 1; i < 11; i++) {
theImages[i] = new Image()
theImages[i].src = "image" + i + ".gif"
}
function animate() {
document.animation.src = theImages[imageNum].src
imageNum++
if(imageNum > 10) {
imageNum = 1
}
}
function slower() {
delay+=10
if(delay > 4000) delay = 4000
}
function faster() {
delay-=10
if(delay < 0) delay = 0
}
</SCRIPT>
<BODY BGCOLOR="white">
<IMG NAME="animation" SRC="image1.gif" ALT="[Animation]"
onLoad="setTimeout('animate()', delay)">
<FORM>
<INPUT TYPE="button" Value="Slower" onClick="slower()">
<INPUT TYPE="button" Value="Faster" onClick="faster()">
</FORM>
</BODY>
See also the示例 for the onAbort, onError, and onLoad event handlers.

参看

Link, onClick, onMouseOut, onMouseOver

属性

border

 A string specifying the width, in pixels, of an image border.

属性源 | Image
只读 |
实现版本 | Navigator 3.0:

描述

The border property reflects the BORDER attribute of the IMG tag. For images created with the Image constructor, the value of the border property is 0.

示例

The following function displays the value of an image's border property if the value is not 0.

function checkBorder(theImage) {
if (theImage.border==0) {
alert('The image has no border!')
}
else alert('The image's border is ' + theImage.border)
}

参看

Image.height, Image.hspace, Image.vspace, Image.width

complete

A boolean value that indicates whether the web browser has completed its attempt to load an image.

属性源 | Image
只读 |
实现版本 | Navigator 3.0:

示例

The following example displays an image and three radio buttons. The user can click the radio buttons to choose which image is displayed. Clicking another button lets the user see the current value of the complete property.

<B>Choose an image:</B>
<BR><INPUT TYPE="radio" NAME="imageChoice" VALUE="image1" CHECKED
onClick="document.images[0].src='f15e.gif'">F-15 Eagle
<BR><INPUT TYPE="radio" NAME="imageChoice" VALUE="image2"
onClick="document.images[0].src='f15e2.gif'">F-15 Eagle 2
<BR><INPUT TYPE="radio" NAME="imageChoice" VALUE="image3"
onClick="document.images[0].src='ah64.gif'">AH-64 Apache
<BR><INPUT TYPE="button" VALUE="Is the image completely loaded?"
onClick="alert('The value of the complete property is '
+ document.images[0].complete)">
<BR>
<IMG NAME="aircraft" SRC="f15e.gif" ALIGN="left" VSPACE="10"><BR>

参看

Image.lowsrc, Image.src

height

A string specifying the height of an image in pixels.

属性源 | Image
只读 |
实现版本 | Navigator 3.0:

描述

The height property reflects the HEIGHT attribute of the IMG tag. For images created with the Image constructor, the value of the height property is the actual, not the displayed, height of the image.

示例

The following function displays the values of an image's height, width, hspace, and vspace properties.

function showImageSize(theImage) {
alert('height=' + theImage.height+
'; width=' + theImage.width +
'; hspace=' + theImage.hspace +
'; vspace=' + theImage.vspace)
}

参看

Image.border, Image.hspace, Image.vspace, Image.width

hspace

A string specifying a margin in pixels between the left and right edges of an image and the surrounding text.

属性源 | Image
只读 |
实现版本 | Navigator 3.0:

描述

The hspace property reflects the HSPACE attribute of the IMG tag. For images created with the Image constructor, the value of the hspace property is 0.

示例

See the示例 for the height property.

参看

Image.border, Image.height, Image.vspace, Image.width

lowsrc

A string specifying the URL of a low-resolution version of an image to be displayed in a document.

属性源 | Image
实现版本 | Navigator 3.0:

描述

The lowsrc property initially reflects the LOWSRC attribute of the IMG tag. The web browser loads the smaller image specified by lowsrc and then replaces it with the larger image specified by the src property. You can change the lowsrc property at any time.

示例

See the示例 for the src property.

参看

Image.complete, Image.src

name

A string specifying the name of an object.

属性源 | Image
只读 |
实现版本 | Navigator 3.0:

安全性

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

描述

Represents the value of the NAME attribute. For images created with the Image constructor, the value of the name property is null.

示例

In the following example, the valueGetter function uses a for loop to iterate over the array of elements on the valueTest form. The msgWindow window displays the names of all the elements on the form:

newWindow=window.open("http://home.netscape.com")
function valueGetter() {
var msgWindow=window.open("")
for (var i = 0; i < newWindow.document.valueTest.elements.length; i++) {
msgWindow.document.write(newWindow.document.valueTest.elements[i].name + "<BR>")
}
}
In the following example, the first statement creates a window called netscapeWin. The second statement displays the value "netscapeHomePage" in the Alert dialog box, because "netscapeHomePage" is the value of the windowName argument of netscapeWin.

netscapeWin=window.open("http://home.netscape.com","netscapeHomePage")
alert(netscapeWin.name)

prototype

Represents the prototype for this class. You can use the prototype to add properties or methods to all instances of a class. For more information, see Function.prototype.

属性源 | Image
实现版本 | Navigator 3.0

src

A string specifying the URL of an image to be displayed in a document.

属性源 | Image
实现版本 | Navigator 3.0:

描述

The src property initially reflects the SRC attribute of the IMG tag. Setting the src property begins loading the new URL into the image area (and aborts the transfer of any image data that is already loading into the same area). Therefore, if you plan to alter the lowsrc property, you should do so before setting the src property.

If the URL in the src property refers to an image that is not the same size as the image cell it is loaded into, the source image is scaled to fit.

When you change the src property of a displayed image, the new image you specify is displayed in the area defined for the original image. For example, suppose an Image object originally displays the file beluga.gif:

<IMG NAME="myImage" SRC="beluga.gif" ALIGN="left"> If you set myImage.src='seaotter.gif', the image seaotter.gif is scaled to fit in the same space originally used by beluga.gif, even if seaotter.gif is not the same size as beluga.gif.

You can change the src property at any time.

示例

The following example displays an image and three radio buttons. The user can click the radio buttons to choose which image is displayed. Each image also uses the lowsrc property to display a low-resolution image.

<SCRIPT>
function displayImage(lowRes,highRes) {
document.images[0].lowsrc=lowRes
document.images[0].src=highRes
}
</SCRIPT>
<FORM NAME="imageForm">
<B>Choose an image:</B>
<BR><INPUT TYPE="radio" NAME="imageChoice" VALUE="image1" CHECKED
onClick="displayImage('f15el.gif','f15e.gif')">F-15 Eagle
<BR><INPUT TYPE="radio" NAME="imageChoice" VALUE="image2"
onClick="displayImage('f15e2l.gif','f15e2.gif')">F-15 Eagle 2
<BR><INPUT TYPE="radio" NAME="imageChoice" VALUE="image3"
onClick="displayImage('ah64l.gif','ah64.gif')">AH-64 Apache
<BR>
<IMG NAME="aircraft" SRC="f15e.gif" LOWSRC="f15el.gif" ALIGN="left" VSPACE="10"><BR>
</FORM>

参看

Image.complete, Image.lowsrc

vspace

A string specifying a margin in pixels between the top and bottom edges of an image and the surrounding text.

属性源 | Image
只读 |
实现版本 | Navigator 3.0:

描述

The vspace property reflects the VSPACE attribute of the IMG tag. For images created with the Image constructor, the value of the vspace property is 0.

示例

See the示例 for the height property.

参看

Image.border, Image.height, Image.hspace, Image.width

width

A string specifying the width of an image in pixels.

属性源 | Image
只读 |
实现版本 | Navigator 3.0:

描述

The width property reflects the WIDTH attribute of the IMG tag. For images created with the Image constructor, the value of the width property is the actual, not the displayed, width of the image.

示例

See the示例 for the height property.

参看

Image.border, Image.height, Image.hspace, Image.vspace

方法

handleEvent

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

方法源 | Image
实现版本 | Navigator 4.0:

语法

handleEvent(event)

参数

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

描述

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


JavaScript语言参考手册_文档

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

Applet

 Includes a Java applet in a web page.

客户端对象 |
实现版本 | Navigator 3.0

创建源

The HTML APPLET tag. The JavaScript runtime engine creates an Applet object corresponding to each applet in your document. It puts these objects in an array in the document.applets property. You access an Applet object by indexing this array.

To define an applet, use standard HTML语法. If you specify the NAME attribute, you can use the value of that attribute to index into the applets array. To refer to an applet in JavaScript, you must supply the MAYSCRIPT attribute in its definition.

描述

The author of an HTML page must permit an applet to access JavaScript by specifying the MAYSCRIPT attribute of the APPLET tag. This prevents an applet from accessing JavaScript on a page without the knowledge of the page author. For example, to allow the musicPicker.class applet access to JavaScript on your page, specify the following:

<APPLET CODE="musicPicker.class" WIDTH=200 HEIGHT=35
NAME="musicApp" MAYSCRIPT> Accessing JavaScript when the MAYSCRIPT attribute is not specified results in an exception.

For more information on using applets, see the JavaScript Guide.

属性概览

All public properties of the applet are available for JavaScript access to the Applet object.

方法概览

All public methods of the applet

示例

The following code launches an applet called musicApp:

<APPLET CODE="musicSelect.class" WIDTH=200 HEIGHT=35
NAME="musicApp" MAYSCRIPT>
</APPLET>

更多示例，请看 JavaScript 指南。

参看

MimeType, Plugin


JavaScript语言参考手册_文档

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

Layer

 Corresponds to a layer in an HTML page and provides a means for manipulating that layer.

客户端对象 |
实现版本 | Navigator 4.0

创建源

The HTML LAYER or ILAYER tag, or using cascading style sheet语法. The JavaScript runtime engine creates a Layer object corresponding to each layer in your document. It puts these objects in an array in the document.layers property. You access a Layer object by indexing this array.

To define a layer, use standard HTML语法. If you specify the ID attribute, you can use the value of that attribute to index into the layers array.

For a complete描述 of layers, see Dynamic HTML in Netscape Communicator 1.

Some layer properties can be directly modified by assignment; for example, "mylayer.visibility = hide". A layer object also has methods that can affect these properties.

事件句柄

  • onMouseOver
  • onMouseOut
  • onLoad
  • onFocus
  • onBlur

属性概览

above | The layer object above this one in z-order, among all layers in the document or the enclosing window object if this layer is topmost.
background | The image to use as the background for the layer's canvas.
bgColor | The color to use as a solid background color for the layer's canvas.
below | The layer object below this one in z-order, among all layers in the document or null if this layer is at the bottom.
clip.bottom | The bottom edge of the clipping rectangle (the part of the layer that is visible.)
clip.height | The height of the clipping rectangle (the part of the layer that is visible.)
clip.left | The left edge of the clipping rectangle (the part of the layer that is visible.)
clip.right | The right edge of the clipping rectangle (the part of the layer that is visible.)
clip.top | The top edge of the clipping rectangle (the part of the layer that is visible.)
clip.width | The width of the clipping rectangle (the part of the layer that is visible.)
document | The layer's associated document.
left | The horizontal position of the layer's left edge, in pixels, relative to the origin of its parent layer.
name | A string specifying the name assigned to the layer through the ID attribute in the LAYER tag.
pageX | The horizontal position of the layer, in pixels, relative to the page.
page y | The vertical position of the layer, in pixels, relative to the page.
parentLayer | The layer object that contains this layer, or the enclosing window object if this layer is not nested in another layer.
siblingAbove | The layer object above this one in z-order, among all layers that share the same parent layer, or null if the layer has no sibling above.
siblingBelow | The layer object below this one in z-order, among all layers that share the same parent layer, or null if layer is at the bottom.
src | A string specifying the URL of the layer's content.
top | The vertical position of the layer's top edge, in pixels, relative to the origin of its parent layer.
visibility | Whether or not the layer is visible.
zIndex | The relative z-order of this layer with respect to its siblings.

方法概览

captureEvents | Sets the window or document to capture all events of the specified type.
handleEvent | 调用指定事件的控制句柄。
load | Changes the source of a layer to the contents of the specified file, and simultaneously changes the width at which the layer's HTML contents will be wrapped.
moveAbove | Stacks this layer above the layer specified in the argument, without changing either layer's horizontal or vertical position.
moveBelow | Stacks this layer below the specified layer, without changing either layer's horizontal or vertical position.
moveBy | Changes the layer position by applying the specified deltas, measured in pixels.
moveTo | Moves the top-left corner of the window to the specified screen coordinates.
moveToAbsolute | Changes the layer position to the specified pixel coordinates within the page (instead of the containing layer.)
releaseEvents | Sets the layer to release captured events of the specified type, sending the event to objects further along the event hierarchy.
resizeBy | Resizes the layer by the specified height and width values (in pixels).
resizeTo | Resizes the layer to have the specified height and width values (in pixels).
routeEvent | Passes a captured event along the normal event hierarchy.

Note

Just as in the case of a document, if you want to define mouse click response for a layer, you must capture onMouseDown and onMouseUp events at the level of the layer and process them as you want.

See "Events in Navigator 4.0" for more details about capturing events.

If an event occurs in a point where multiple layers overlap, the topmost layer gets the event, even if it is transparent. However, if a layer is hidden, it does not get events.

属性

above

 The layer object above this one in z-order, among all layers in the document or the enclosing window object if this layer is topmost.

属性源 | Layer
只读 |
实现版本 | Navigator 4.0

background

The image to use as the background for the layer's canvas (which is the part of the layer within the clip rectangle).

属性源 | Layer
实现版本 | Navigator 4.0

描述

Each layer has a background property, whose value is an image object, whose src attribute is a URL that indicates the image to use to provide a tiled backdrop. The value is null if the layer has no backdrop. For example:

layer.background.src = "fishbg.gif";

bgColor

A string specifying the color to use as a solid background color for the layer's canvas (the part of the layer within the clip rectangle).

属性源 | Layer
实现版本 | Navigator 4.0

描述

The bgColor 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 BGCOLOR attribute of the BODY tag.

You can set the bgColor property at any time.

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 background color of the myLayer layer's canvas to aqua using a string literal:

myLayer.bgColor="aqua" The following example sets the background color of the myLayer layer's canvas to aqua using a hexadecimal triplet:

myLayer.bgColor="00FFFF"

参看

Layer.bgColor

below

The layer object below this one in z-order, among all layers in the document or null if this layer is at the bottom.

属性源 | Layer
只读 |
实现版本 | Navigator 4.0

clip.bottom

The bottom edge of the clipping rectangle (the part of the layer that is visible.) Any part of a layer that is outside the clipping rectangle is not displayed.

属性源 | Layer
实现版本 | Navigator 4.0

clip.height

The height of the clipping rectangle (the part of the layer that is visible.) Any part of a layer that is outside the clipping rectangle is not displayed.

属性源 | Layer
实现版本 | Navigator 4.0

clip.left

The left edge of the clipping rectangle (the part of the layer that is visible.) Any part of a layer that is outside the clipping rectangle is not displayed.

属性源 | Layer
实现版本 | Navigator 4.0

clip.right

The right edge of the clipping rectangle (the part of the layer that is visible.) Any part of a layer that is outside the clipping rectangle is not displayed.

属性源 | Layer
实现版本 | Navigator 4.0

clip.top

The top edge of the clipping rectangle (the part of the layer that is visible.) Any part of a layer that is outside the clipping rectangle is not displayed.

属性源 | Layer
实现版本 | Navigator 4.0

clip.width

The width of the clipping rectangle (the part of the layer that is visible.) Any part of a layer that is outside the clipping rectangle is not displayed.

属性源 | Layer
实现版本 | Navigator 4.0

document

The layer's associated document.

属性源 | Layer
只读 |
实现版本 | Navigator 4.0

描述

Each layer object contains its own document object. This object can be used to access the images, applets, embeds, links, anchors and layers that are contained within the layer. Methods of the document object can also be invoked to change the contents of the layer.

left

The horizontal position of the layer's left edge, in pixels, relative to the origin of its parent layer.

属性源 | Layer
实现版本 | Navigator 4.0

name

A string specifying the name assigned to the layer through the ID attribute in the LAYER tag.

属性源 | Layer
只读 |
实现版本 | Navigator 4.0

pageX

The horizontal position of the layer, in pixels, relative to the page.

属性源 | Layer
实现版本 | Navigator 4.0

pageY

The vertical position of the layer, in pixels, relative to the page.

属性源 | Layer
实现版本 | Navigator 4.0

parentLayer

The layer object that contains this layer, or the enclosing window object if this layer is not nested in another layer.

属性源 | Layer
只读 |
实现版本 | Navigator 4.0

siblingAbove

The layer object above this one in z-order, among all layers that share the same parent layer or null if the layer has no sibling above.

属性源 | Layer
只读 |
实现版本 | Navigator 4.0

siblingBelow

The layer object below this one in z-order, among all layers that share the same parent layer or null if layer is at the bottom.

属性源 | Layer
只读 |
实现版本 | Navigator 4.0

src

A URL string specifying the source of the layer's content. Corresponds to the SRC attribute.

属性源 | Layer
实现版本 | Navigator 4.0

top

The top property is a synonym for the topmost Navigator window, which is a document window or web browser window.

属性源 | Layer
只读 |
实现版本 | Navigator 4.0

描述

The top property refers to the topmost window that contains frames or nested framesets. Use the top property to refer to this ancestor window.

The value of the top property is

<object objectReference> where objectReference is an internal reference.

示例

The statement top.close() closes the topmost ancestor window.

The statement top.length specifies the number of frames contained within the topmost ancestor window. When the topmost ancestor is defined as follows, top.length returns three:

<FRAMESET COLS="30%,40%,30%">
<FRAME SRC=child1.htm NAME="childFrame1">
<FRAME SRC=child2.htm NAME="childFrame2">
<FRAME SRC=child3.htm NAME="childFrame3">
</FRAMESET>

visibility

Whether or not the layer is visible.

属性源 | Layer
实现版本 | Navigator 4.0

描述

A value of show means show the layer; hide means hide the layer; inherit means inherit the visibility of the parent layer.

zIndex

The relative z-order of this layer with respect to its siblings.

方法源 | Layer
实现版本 | Navigator 4.0

描述

Sibling layers with lower numbered z-indexes are stacked underneath this layer. The value of zIndex must be 0 or a positive integer.

方法

captureEvents

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

方法源 | Layer
实现版本 | Navigator 4.0

语法

captureEvents(eventType)

参数

eventTypeType of event to be captured. Available event types are listed with event.

描述

When a window with frames wants to capture events in pages loaded from different locations (servers), you need to use captureEvents in a signed script and precede it with enableExternalCapture. For more information and an example, see enableExternalCapture.

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

handleEvent

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

方法源 | Layer
实现版本 | Navigator 4.0

语法

handleEvent(event)

参数

eventName of an event for which the specified object has an event handler.

描述

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

load

Changes the source of a layer to the contents of the specified file and simultaneously changes the width at which the layer's HTML contents are wrapped.

方法源 | Layer
实现版本 | Navigator 4.0

语法

load(sourcestring, width)

参数

sourcestring | A string indicating the external file name.
width | The width of the layer as a pixel value.

moveAbove

Stacks this layer above the layer specified in the argument, without changing either layer's horizontal or vertical position. After re-stacking, both layers will share the same parent layer.

方法源 | Layer
实现版本 | Navigator 4.0

语法

moveAbove(aLayer)

参数

aLayerThe layer above which to move the current layer.

moveBelow

Stacks this layer below the specified layer, without changing either layer's horizontal or vertical position. After re-stacking, both layers will share the same parent layer.

方法源 | Layer
实现版本 | Navigator 4.0

语法

moveBelow(aLayer)

参数

aLayerThe layer below which to move the current layer.

moveBy

Changes the layer position by applying the specified deltas, measured in pixels.

方法源 | Layer
实现版本 | Navigator 4.0

语法

moveBy(horizontal, vertical)

参数

horizontal | The number of pixels by which to move the layer horizontally.
vertical | The number of pixels by which to move the layer vertically.

moveTo

Moves the top-left corner of the window to the specified screen coordinates.

方法源 | Layer
实现版本 | Navigator 4.0

语法

moveTo(x-coordinate, y-coordinate)

参数

x-coordinate | An integer representing the top edge of the window in screen coordinates.
y-coordinate | An integer representing the left edge of the window in screen coordinates.

安全性

To move a window offscreen, call the moveTo method in a signed script. 要获取 Navigator 4.0 中关于安全性更多的信息，请看“JavaScript 指南”中的第七章“JavaScript 安全性”。

描述

Changes the layer position to the specified pixel coordinates within the containing layer. For ILayers, moves the layer relative to the natural inflow position of the layer.

参看

 Layer.moveBy

moveToAbsolute

Changes the layer position to the specified pixel coordinates within the page (instead of the containing layer.)

方法源 | Layer
实现版本 | Navigator 4.0

语法

moveToAbsolute(x, y)

参数

x | An integer representing the top edge of the window in pixel coordinates.
y | An integer representing the left edge of the window in pixel coordinates.

描述

This method is equivalent to setting both the pageX and pageY properties of the layer object.

releaseEvents

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

方法源 | Layer
实现版本 | Navigator 4.0

语法

releaseEvents(eventType)

参数

eventTypeType of event to be captured.

描述

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 works in tandem with captureEvents, routeEvent, and handleEvent. For more information, see "Events in Navigator 4.0".

resizeBy

Resizes the layer by the specified height and width values (in pixels).

方法源 | Layer
实现版本 | Navigator 4.0

语法

resizeBy(width, height)

参数

width | The number of pixels by which to resize the layer horizontally.
height | The number of pixels by which to resize the layer vertically.

描述

This does not layout any HTML contained in the layer again. Instead, the layer contents may be clipped by the new boundaries of the layer. This method has the same effect as adding width and height to clip.width and clip.height.

resizeTo

Resizes the layer to have the specified height and width values (in pixels).

方法源 | Layer
实现版本 | Navigator 4.0

描述

This does not layout any HTML contained in the layer again. Instead, the layer contents may be clipped by the new boundaries of the layer.

语法

resizeBy(width, height)

参数

width | An integer representing the layer's width in pixels.
height | An integer representing the layer's height in pixels.

描述

This method has the same effect setting clip.width and clip.height.

routeEvent

Passes a captured event along the normal event hierarchy.

方法源 | Layer
实现版本 | Navigator 4.0

语法

routeEvent(event)

参数

eventThe event to route.

描述

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".

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


JavaScript语言参考手册_事件和事件句柄

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

第九章
事件和事件句柄

This chapter contains the event object and the event handlers that are used with客户端对象s in JavaScript to evoke particular actions. In addition, it contains general information about using events and event handlers.

表 9.1 列出了本章的一个对象。

表 9.1 与事件相关的对象
对象 | 描述
event | Represents a JavaScript event. Passed to every event handler.

表 9.2 总览 JavaScript 事件句柄。

表 9.2 事件及对应的事件句柄。
事件 | 事件句柄 | 事件发生的条件……
abort | onAbort | The user aborts the loading of an image (for example by clicking a link or clicking the Stop button).
blur | onBlur | A form element loses focus or when a window or frame loses focus.
change | onChange | A select, text, or textarea field loses focus and its value has been modified.
click | onClick | An object on a form is clicked.
dblclick | onDblClick | The user double-clicks a form element or a link.
dragdrop | onDragDrop | The user drops an object onto the browser window, such as dropping a file on the browser window.
error | onError | The loading of a document or image causes an error.
focus | onFocus | A window, frame, or frameset receives focus or when a form element receives input focus.
keydown | onKeyDown | The user depresses a key.
keypress | onKeyPress | The user presses or holds down a key.
keyup | onKeyUp | The user releases a key.
load | onLoad | The browser finishes loading a window or all of the frames within a FRAMESET tag.
mousedown | onMouseDown | The user depresses a mouse button.
mousemove | onMouseMove | The user moves the cursor.
mouseout | onMouseOut | The cursor leaves an area (client-side image map) or link from inside that area or link.
mouseover | onMouseOver | The cursor moves over an object or area from outside that object or area.
mouseup | onMouseUp | The user releases a mouse button.
move | onMove | The user or script moves a window or frame.
reset | onReset | The user resets a form (clicks a Reset button).
resize | onResize | The user or script resizes a window or frame.
select | onSelect | The user selects some of the text within a text or textarea field.
submit | onSubmit | The user submits a form.
unload | onUnload | The user exits a document.

General Information about Events

JavaScript applications in the browser are largely event-driven. Events are actions that occur usually as a result of something the user does. For example, clicking a button is an event, as is changing a text field or moving the mouse over a link. For your script to react to an event, you define event handlers, such as onChangeandonClick.

定义事件句柄

If an event applies to an HTML tag, then you can define an事件适用对象it. The name of an event handler is the name of the event, preceded by "on". For example, the事件适用对象the focus event is onFocus.

To create an事件适用对象an HTML tag, add an event handler attribute to the tag. Put JavaScript code in quotation marks as the attribute value. The general语法 is

<TAG eventHandler="JavaScript Code"> where TAG is an HTML tag and eventHandler is the name of the event handler. For example, suppose you have created a JavaScript function called compute. You can cause the browser to perform this function when the user clicks a button by assigning the function call to the button's onClick event handler:

<INPUT TYPE="button" VALUE="Calculate" onClick="compute(this.form)"> You can put any JavaScript statements inside the quotation marks following onClick. These statements are executed when the user clicks the button. If you want to include more than one statement, separate statements with a semicolon.

When you create an event handler, the corresponding JavaScript object gets a property with the name of the event handler in lower case letters. (In Navigator 4.0, you can also use the mixed case name of the事件适用对象the property name.) This property allows you to access the object's event handler. For example, in the preceding example, JavaScript creates a Button object with an onclick property whose value is "compute(this.form)".

Chapter 7, "JavaScript Security," in JavaScript Guide contains more information about creating and using event handlers.

Events in Navigator 4.0

In Navigator 4.0, JavaScript includes event objects as well as event handlers. Each event has an event object associated with it. The event object provides information about the event, such as the type of event and the location of the cursor at the time of the event. When an event occurs, and if an event handler has been written to handle the event, the event object is sent as an argument to the event handler.

Typically, the object on which the event occurs handles the event. For example, when the user clicks a button, it is often the button's event handler that handles the event. Sometimes you may want the Window or document object to handle certain types of events. For example, you may want the document object to handle all MouseDown events no matter where they occur in the document. JavaScript's event capturing model allows you to define methods that capture and handle events before they reach their intended target.

In addition to providing the event object, Navigator 4.0 allows a Window or document to capture and handle an event before it reaches its intended target. To accomplish this, the Window, document, and Layer objects have these new methods:

  • captureEvents
  • releaseEvents
  • routeEvent
  • handleEvent (Not a method of the Layer object)
For example, suppose you want to capture all click events that occur in a window. First, you need to set up the window to capture click events:

window.captureEvents(Event.CLICK); The argument to Window.captureEvents is a property of the event object and indicates the type of event to capture. To capture multiple events, the argument is a list separated by vertical slashes (|). For example:

window.captureEvents(Event.CLICK | Event.MOUSEDOWN | Event.MOUSEUP) Next, you need to define a function that handles the event. The argument evnt is the event object for the event.

function clickHandler(evnt) {
//What goes here depends on how you want to handle the event.
//This is described below.
}
You have four options for handling the event:

  • Return true. In the case of a link, the link is followed and no other event handler is checked. If the event cannot be canceled, this ends the event handling for that event.
    • function clickHandler(evnt) { return true; }

  • Return false. In the case of a link, the link is not followed. If the event is non-cancelable, this ends the event handling for that event.
    • function clickHandler(evnt) { return false; }

  • Call routeEvent. JavaScript looks for other event handlers for the event. If another object is attempting to capture the event (such as the document), JavaScript calls its event handler. If no other object is attempting to capture the event, JavaScript looks for an事件适用对象the event's original target (such as a button). The routeEvent method returns the value returned by the event handler. The capturing object can look at this return value and decide how to proceed.
    • function clickHandler(evnt) {
    var retval = routeEvent(evnt);
    if (retval == false) return false;
    else return true;
    }     Note: When routeEvent calls an event handler, the event handler is activated. If routeEvent calls an event handler whose function is to display a new page, the action takes place without returning to the capturing object.

  • Call the handleEvent method of an event receiver. Any object that can register event handlers is an event receiver. This method explicitly calls the event handler of the event receiver and bypasses the capturing hierarchy. For example, if you wanted all click events to go to the first link on the page, you could use:
    • function clickHandler(evnt) {
    window.document.links[0].handleEvent(evnt);
    }     As long as the link has an onClick handler, the link handles any click event it receives.

Finally, you need to register the function as the window's事件适用对象that event:

window.onClick = clickHandler;

注意

If a window with frames wants to capture events in pages loaded from different locations, you need to use captureEvents in a signed script and call Window.enableExternalCapture. In the following example, the window and document capture and release events:

<HTML>
<SCRIPT>
function fun1(evnt) {
alert ("The window got an event of type: " + evnt.type +
" and will call routeEvent.");
window.routeEvent(evnt);
alert ("The window returned from routeEvent.");
return true;
}
function fun2(evnt) {
alert ("The document got an event of type: " + evnt.type);
return false;
}
function setWindowCapture() {
window.captureEvents(Event.CLICK);
}
function releaseWindowCapture() {
window.releaseEvents(Event.CLICK);
}
function setDocCapture() {
document.captureEvents(Event.CLICK);
}
function releaseDocCapture() {
document.releaseEvents(Event.CLICK);
}
window.onclick=fun1;
document.onclick=fun2;
</SCRIPT>
...
</HTML>

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


JavaScript语言参考手册_事件和事件句柄

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

event

 The event object contains properties that describe a JavaScript event, and is passed as an argument to an event handler when the event occurs.

客户端对象 |
实现版本 | Navigator 4.0
 In the case of a mouse-down event, for example, the event object contains the type of event (in this case MouseDown), the x and y position of the cursor at the time of the event, a number representing the mouse button used, and a field containing the modifier keys (Control, Alt, Meta, or Shift) that were depressed at the time of the event. The properties used within the event object vary from one type of event to another. This variation is provided in the描述s of individual event handlers.

For more information, see "General Information about Events".

创建源

event objects are created by Communicator when an event occurs. You do not create them yourself.

安全性

Setting any property of this object requires the UniversalBrowserWrite privilege. In addition, getting the data property of the DragDrop event requires the UniversalBrowserRead privilege. 要获取 Navigator 4.0 中关于安全性更多的信息，请看“JavaScript 指南”中的第七章“JavaScript 安全性”。

属性概览

Not all of these properties are relevant to each event type. To learn which properties are used by an event, see the "Event object properties used" section of the individual event handler.

target | String representing the object to which the event was originally sent. (All events)
type | String representing the event type. (All events)
data | Returns an array of strings containing the URLs of the dropped objects. Passed with the DragDrop event.
height | Represents the height of the window or frame.
layerX | Number specifying either the object width when passed with the resize event, or the cursor's horizontal position in pixels relative to the layer in which the event occurred. Note that layerX is synonymous with x.
layerY | Number specifying either the object height when passed with the resize event, or the cursor's vertical position in pixels relative to the layer in which the event occurred. Note that layerY is synonymous with y.
modifiers | String specifying the modifier keys associated with a mouse or key event. Modifier key values are: ALT_MASK, CONTROL_MASK, SHIFT_MASK, and META_MASK.
pageX | Number specifying the cursor's horizontal position in pixels, relative to the page.
pageY | Number specifying the cursor's vertical position in pixels relative to the page.
screenX | Number specifying the cursor's horizontal position in pixels, relative to the screen.
screenY | Number specifying the cursor's vertical position in pixels, relative to the screen.
which | Number specifying either the mouse button that was pressed or the ASCII value of a pressed key. For a mouse, 1 is the left button, 2 is the middle button, and 3 is the right button.
width | Represents the width of the window or frame.

示例

The following example uses the event object to provide the type of event to the alert message. <A HREF="http://home.netscape.com" onClick='alert("Link got an event: "
+ event.type)'>Click for link event</A> The following example uses the event object in an explicitly called event handler.

<SCRIPT>
function fun1(evnt) {
alert ("Document got an event: " + evnt.type);
alert ("x position is " + evnt.layerX);
alert ("y position is " + evnt.layerY);
if (evnt.modifiers & Event.ALT_MASK)
alert ("Alt key was down for event.");
return true;
}
document.onmousedown = fun1;
</SCRIPT>


JavaScript语言参考手册_事件和事件句柄

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

onAbort

 当 abort 事件发生时执行的 JavaScript 代码。当用户中止图像载入(如单击某链接或按停止按钮)时触发 abort 事件。

事件适用对象 | Image
实现版本 | Navigator 3.0

语法

onAbort="handlerText"

参数

handlerText JavaScript 代码或对一个 JavaScript 函数的调用。

使用的事件属性

type | 标明了事件的类型。
target | 标明了事件原来发送的对象。

示例

下面的例子中，Image 对象的 onAbort 事件句柄将在用户中止图像载入的时候显示一条信息。：

<IMG NAME="aircraft" SRC="f15e.gif"
onAbort="alert('你看不到图像喽！')">

参看

onError, onLoad

要获得关于事件句柄的常规信息，请看“事件的常规信息”。

要获得关于事件对象的信息，请看事件。


JavaScript语言参考手册_事件和事件句柄

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

onBlur

 Executes JavaScript code when a blur event occurs; that is, when a form element loses focus or when a window or frame loses focus.

事件适用对象 | Button, Checkbox, FileUpload, Layer, Password, Radio, Reset, Select, Submit, Text, Textarea, Window
实现版本 | Navigator 2.0 Navigator 3.0: event handler of Button, Checkbox, FileUpload, Frame, Password, Radio, Reset, Submit, and Window

语法

onBlur="handlerText"

参数

handlerTextJavaScript 代码或对一个 JavaScript 函数的调用。

描述

The blur event can result from a call to the Window.blur method or from the user clicking the mouse on another object or window or tabbing with the keyboard.

For windows, frames, and framesets, onBlur specifies JavaScript code to execute when a window loses focus.

A frame's onBlur event handler overrides an onBlur event handler in the BODY tag of the document loaded into frame.

Note In Navigator 3.0, on some platforms placing an onBlur event handler in a FRAMESET tag has no effect.

使用的事件属性

type | 标明了事件的类型。
target | 标明了事件原来发送的对象。

示例

示例 1: Validate form input. In the following example, userName is a required text field. When a user attempts to leave the field, the onBlur event handler calls the required function to confirm that userName has a legal value.

<INPUT TYPE="text" VALUE="" NAME="userName"
onBlur="required(this.value)"> 示例 2: Change the background color of a window. In the following example, a window's onBlur and onFocus event handlers change the window's background color depending on whether the window has focus.

<BODY BGCOLOR="lightgrey"
onBlur="document.bgColor='lightgrey'"
onFocus="document.bgColor='antiquewhite'">
示例 3: Change the background color of a frame. The following example creates four frames. The source for each frame, onblur2.html has the BODY tag with the onBlur and onFocus event handlers shown in Example 1. When the document loads, all frames are light grey. When the user clicks a frame, the onFocus event handler changes the frame's background color to antique white. The frame that loses focus is changed to light grey. Note that the onBlur and onFocus event handlers are within the BODY tag, not the FRAME tag.

<FRAMESET ROWS="50%,50%" COLS="40%,60%">
<FRAME SRC=onblur2.html NAME="frame1">
<FRAME SRC=onblur2.html NAME="frame2">
<FRAME SRC=onblur2.html NAME="frame3">
<FRAME SRC=onblur2.html NAME="frame4">
</FRAMESET>
The following code has the same effect as the previous code, but is implemented differently. The onFocus and onBlur event handlers are associated with the frame, not the document. The onBlur and onFocus event handlers for the frame are specified by setting the onblur and onfocus properties.

<SCRIPT>
function setUpHandlers() {
for (var i = 0; i < frames.length; i++) {
frames[i].onfocus=new Function("document.bgColor='antiquewhite'")
frames[i].onblur=new Function("document.bgColor='lightgrey'")
}
}
</SCRIPT>
<FRAMESET ROWS="50%,50%" COLS="40%,60%" onLoad=setUpHandlers()>
<FRAME SRC=onblur2.html NAME="frame1">
<FRAME SRC=onblur2.html NAME="frame2">
<FRAME SRC=onblur2.html NAME="frame3">
<FRAME SRC=onblur2.html NAME="frame4">
</FRAMESET>
示例 4: Close a window. In the following example, a window's onBlur event handler closes the window when the window loses focus.

<BODY onBlur="window.close()">
This is some text
</BODY>

参看

onChange, onFocus

要获得关于事件句柄的常规信息，请看“事件的常规信息”。

要获得关于事件对象的信息，请看事件。


JavaScript语言参考手册_事件和事件句柄

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

onChange

 当 change 事件发生时执行的 JavaScript 代码。当一个 Select、Text、或 Textarea 域失去焦点并更改值时触发 change 事件。

事件适用对象 | FileUpload, Select, Text, Textarea
实现版本 | Navigator 2.0:适用于 Select, Text, 和 Textarea Navigator 3.0: 添加了对 FileUpload 的适用

语法

onChange="handlerText"

参数

handlerTextJavaScript 代码或对一个 JavaScript 函数的调用。

描述

使用 onChange 在用户修改数据后进行校验。

使用的事件属性

type | 标明了事件的类型。
target | 标明了事件原来发送的对象。

示例

在下面的例子中，userName 是一个文本域。当用户更改文本并离开该域时，onChange 事件句柄会调用 checkValue 函数确认 userName 中是否存放了合法值。

<INPUT TYPE="text" VALUE="" NAME="userName" onChange="checkValue(this.value)">

参看

onBlur, onFocus

要获得关于事件句柄的常规信息，请看“事件的常规信息”。

要获得关于事件对象的信息，请看事件。


JavaScript语言参考手册_事件和事件句柄

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

onClick

 Executes JavaScript code when a click event occurs; that is, when an object on a form is clicked. (A Click event is a combination of the MouseDown and MouseUp events).

事件适用对象 | Button, document, Checkbox, Link, Radio, Reset, Submit
实现版本 | Navigator 2.0 Navigator 3.0: 添加了 the ability to return false to cancel the action associated with a click event

语法

onClick="handlerText"

参数

handlerTextJavaScript 代码或对一个 JavaScript 函数的调用。

使用的事件属性

type | 标明了事件的类型。
target | 标明了事件原来发送的对象。
When a link is clicked, layerX, layerY, pageX, pageY, screenX, screenY | Represent the cursor location at the time the event occurred.
which | Represents 1 for a left-mouse click and 3 for a right-mouse click.
modifiers | Contains the list of modifier keys held down when the event occurred.

描述

For checkboxes, links, radio buttons, reset buttons, and submit buttons, onClick can return false to cancel the action normally associated with a click event.

For example, the following code creates a link that, when clicked, displays a confirm dialog box. If the user clicks the link and then chooses cancel, the page specified by the link is not loaded.

<A HREF = "http://home.netscape.com/"
onClick="return confirm('Load Netscape home page?')">
Netscape</A> If the event handler returns false, the default action of the object is canceled as follows:

  • Buttons--no default action; nothing is canceled

  • Radio buttons and checkboxes--nothing is set

  • Submit buttons--form is not submitted

  • Reset buttons--form is not reset
    • Note In Navigator 3.0, on some platforms, returning false in an onClick事件适用对象a reset button has no effect.

示例

 示例 1: Call a function when a user clicks a button. Suppose you have created a JavaScript function called compute. You can execute the compute function when the user clicks a button by calling the function in the onClick event handler, as follows:

<INPUT TYPE="button" VALUE="Calculate" onClick="compute(this.form)"> In the preceding example, the keyword this refers to the current object; in this case, the Calculate button. The construct this.form refers to the form containing the button.

For another example, suppose you have created a JavaScript function called pickRandomURL that lets you select a URL at random. You can use onClick to specify a value for the HREF attribute of the A tag dynamically, as shown in the following example:

<A HREF=""
onClick="this.href=pickRandomURL()"
onMouseOver="window.status='Pick a random URL'; return true">
Go!</A>
In the above example, onMouseOver specifies a custom message for the browser's status bar when the user places the mouse pointer over the Go! anchor. As this example shows, you must return true to set the window.status property in the onMouseOver event handler.

示例 2: Cancel the checking of a checkbox. The following example creates a checkbox with onClick. The event handler displays a confirm that warns the user that checking the checkbox purges all files. If the user chooses Cancel, onClick returns false and the checkbox is not checked.

<INPUT TYPE="checkbox" NAME="check1" VALUE="check1"
onClick="return confirm('This purges all your files. Are you sure?')"> Remove files

参看

要获得关于事件句柄的常规信息，请看“事件的常规信息”。

要获得关于事件对象的信息，请看事件。


JavaScript语言参考手册_事件和事件句柄

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

onDblClick

 当 DblClick 事件发生时执行的 JavaScript 代码。当用户双击表单元素或链接时触发 DblClick 事件。

事件适用对象 | document, Link
实现版本 | Navigator 4.0

语法

onDblClick="handlerText"

参数

handlerText JavaScript 代码或对一个 JavaScript 函数的调用。

注解

DblClick 尚未在 Macintosh 上实现。

使用的事件属性

type | 标明了事件的类型。
target | 标明了事件原来发送的对象。
layerX, layerY, pageX, pageY, screenX, screenY | 标明了发生该事件时鼠标指针的位置。
which | 如果用鼠标左键双击，则为 1；如果用鼠标右键双击，则为 3。Represents 1 for a left-mouse double-click and 3 for a right-mouse double-click.
modifiers | 包含了发生该事件时按住的控制键清单。

参看

要获得关于事件句柄的常规信息，请看“事件的常规信息”。

要获得关于事件对象的信息，请看事件。


JavaScript语言参考手册_事件和事件句柄

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

onDragDrop

 Executes JavaScript code when a DragDrop event occurs; that is, when the user drops an object onto the browser window, such as dropping a file.

事件适用对象 | Window
实现版本 | Navigator 4.0

语法

onDragDrop="handlerText"

参数

handlerTextJavaScript 代码或对一个 JavaScript 函数的调用。

使用的事件属性

type | 标明了事件的类型。
target | 标明了事件原来发送的对象。
data | Returns an Array of Strings containing the URLs of the dropped objects.
modifiers | Contains the list of modifier keys held down when the event occurred.
screenX, screenY | Represent the cursor location at the time the event occurred.

安全性

Getting the data property of the DragDrop event requires the UniversalBrowserRead privilege. 要获取 Navigator 4.0 中关于安全性更多的信息，请看“JavaScript 指南”中的第七章“JavaScript 安全性”。

描述

The DragDrop event is fired whenever a system item (file, shortcut, and so on) is dropped onto the browser window using the native system's drag and drop mechanism. The normal response for the browser is to attempt to load the item into the browser window. If the事件适用对象the DragDrop event returns true, the browser loads the item normally. If the event handler returns false, the drag and drop is canceled.

参看

要获得关于事件句柄的常规信息，请看“事件的常规信息”。

要获得关于事件对象的信息，请看事件。


JavaScript语言参考手册_事件和事件句柄

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

onError

 Executes JavaScript code when an error event occurs; that is, when the loading of a document or image causes an error.

事件适用对象 | Image, Window
实现版本 | Navigator 3.0

语法

onError="handlerText"

参数

handlerTextJavaScript 代码或对一个 JavaScript 函数的调用。

描述

An error event occurs only when a JavaScript语法 or runtime error occurs, not when a browser error occurs. For example, if you try set window.location.href='notThere.html' and notThere.html does not exist, the resulting error message is a browser error message; therefore, onError would not intercept that message. However, an error event is triggered by a bad URL within an IMG tag or by corrupted image data.

window.onerror applies only to errors that occur in the window containing window.onerror, not in other windows.

onError can be any of the following:

  • null to suppress all JavaScript error dialogs. Setting window.onerror to null means your users won't see JavaScript errors caused by your own code.

  • The name of a function that handles errors (arguments are message text, URL, and line number of the offending line). To suppress the standard JavaScript error dialog, the function must return true. See Example 3 below.

  • A variable or property that contains null or a valid function reference.
If you write an error-handling function, you have three options for reporting errors:

  • Trace errors but let the standard JavaScript dialog report them (use an error handling function that returns false or does not return a value)

  • Report errors yourself and disable the standard error dialog (use an error handling function that returns true)

  • Turn off all error reporting (set the onError event handler to null)

使用的事件属性

type | 标明了事件的类型。
target | 标明了事件原来发送的对象。

示例

示例 1: Null event handler. In the following IMG tag, the code onError="null" suppresses error messages if errors occur when the image loads.

<IMG NAME="imageBad1" SRC="corrupt.gif" ALIGN="left" BORDER="2"
onError="null"> 示例 2: Null事件适用对象a window. The onError事件适用对象windows cannot be expressed in HTML. Therefore, you must spell it all lowercase and set it in a SCRIPT tag. The following code assigns null to the onError handler for the entire window, not just the Image object. This suppresses all JavaScript error messages, including those for the Image object.

<SCRIPT>
window.onerror=null
</SCRIPT>
<IMG NAME="imageBad1" SRC="corrupt.gif" ALIGN="left" BORDER="2"> However, if the Image object has a custom onError event handler, the handler would execute if the image had an error. This is because window.onerror=null suppresses JavaScript error messages, not onError event handlers.

<SCRIPT>
window.onerror=null
function myErrorFunc() {
alert("The image had a nasty error.")
}
</SCRIPT>
<IMG NAME="imageBad1" SRC="corrupt.gif" ALIGN="left" BORDER="2"
onError="myErrorFunc()">
In the following example, window.onerror=null suppresses all error reporting. Without onerror=null, the code would cause a stack overflow error because of infinite recursion.

<SCRIPT>
window.onerror = null;
function testErrorFunction() {
testErrorFunction();
}
</SCRIPT>
<BODY onload="testErrorFunction()">
test message
</BODY> 示例 3: Error handling function. The following example defines a function, myOnError, that intercepts JavaScript errors. The function uses three arrays to store the message, URL, and line number for each error. When the user clicks the Display Error Report button, the displayErrors function opens a window and creates an error report in that window. Note that the function returns true to suppress the standard JavaScript error dialog.

<SCRIPT>
window.onerror = myOnError
msgArray = new Array()
urlArray = new Array()
lnoArray = new Array()
function myOnError(msg, url, lno) {
msgArray[msgArray.length] = msg
urlArray[urlArray.length] = url
lnoArray[lnoArray.length] = lno
return true
}
function displayErrors() {
win2=window.open('','window2','scrollbars=yes')
win2.document.writeln('<B>Error Report</B><P>')
   for (var i=0; i < msgArray.length; i++) {
win2.document.writeln('<B>Error in file:</B> ' + urlArray[i] + '<BR>')
win2.document.writeln('<B>Line number:</B> ' + lnoArray[i] + '<BR>')
win2.document.writeln('<B>Message:</B> ' + msgArray[i] + '<P>')
}
win2.document.close()
}
</SCRIPT>
<BODY onload="noSuchFunction()">
<FORM>
<BR><INPUT TYPE="button" VALUE="This button has a语法 error"
onClick="alert('unterminated string)">
<P><INPUT TYPE="button" VALUE="Display Error Report"
onClick="displayErrors()">
</FORM>
This example produces the following output:

Error Report Error in file: file:///c%7C/temp/onerror.html
Line number: 34
Message: unterminated string literal Error in file: file:///c%7C/temp/onerror.html
Line number: 34
Message: missing ) after argument list Error in file: file:///c%7C/temp/onerror.html
Line number: 30
Message: noSuchFunction is not defined 示例 4: Event handler calls a function. In the following IMG tag, onError calls the function badImage if errors occur when the image loads.

<SCRIPT>
function badImage(theImage) {
alert('Error: ' + theImage.name + ' did not load properly.')
}
</SCRIPT>
<FORM>
<IMG NAME="imageBad2" SRC="orca.gif" ALIGN="left" BORDER="2"
onError="badImage(this)">
</FORM>

参看

onAbort, onLoad

要获得关于事件句柄的常规信息，请看“事件的常规信息”。

要获得关于事件对象的信息，请看事件。


JavaScript语言参考手册_事件和事件句柄

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

onFocus

 Executes JavaScript code when a focus event occurs; that is, when a window, frame, or frameset receives focus or when a form element receives input focus.

事件适用对象 | Button, Checkbox, FileUpload, Layer, Password, Radio, Reset, Select, Submit, Text, Textarea, Window
实现版本 | Navigator 2.0 Navigator 3.0: event handler of Button, Checkbox, FileUpload, Frame, Password, Radio, Reset, Submit, and Window Navigator 4.0: event handler of Layer

语法

onFocus="handlerText"

参数

handlerTextJavaScript 代码或对一个 JavaScript 函数的调用。

描述

The focus event can result from a focus method or from the user clicking the mouse on an object or window or tabbing with the keyboard. Selecting within a field results in a select event, not a focus event. onFocus executes JavaScript code when a focus event occurs.

A frame's onFocus event handler overrides an onFocus event handler in the BODY tag of the document loaded into frame.

Note that placing an alert in an onFocus event handler results in recurrent alerts: when you press OK to dismiss the alert, the underlying window gains focus again and produces another focus event.

Note

In Navigator 3.0, on some platforms, placing an onFocus event handler in a FRAMESET tag has no effect.

使用的事件属性

type | 标明了事件的类型。
target | 标明了事件原来发送的对象。

示例

The following example uses an onFocus handler in the valueField Textarea object to call the valueCheck function.

<INPUT TYPE="textarea" VALUE="" NAME="valueField"
onFocus="valueCheck()"> See also示例 for onBlur.

参看

onBlur, onChange

要获得关于事件句柄的常规信息，请看“事件的常规信息”。

要获得关于事件对象的信息，请看事件。


JavaScript语言参考手册_事件和事件句柄

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

onKeyDown

 Executes JavaScript code when a KeyDown event occurs; that is, when the user depresses a key.

事件适用对象 | document, Image, Link, Textarea
实现版本 | Navigator 4.0

语法

onKeyDown="handlerText"

参数

handlerTextJavaScript 代码或对一个 JavaScript 函数的调用。

使用的事件属性

type | 标明了事件的类型。
target | 标明了事件原来发送的对象。
layerX, layerY, pageX, pageY, screenX, screenY | For an event over a window, these represent the cursor location at the time the event occurred. For an event over a form, they represent the position of the form element.
which | Represents the ASCII value of the key pressed. To get the actual letter, number, or symbol of the pressed key, use the String.fromCharCode 方法。 To set this 属性 when the ASCII value is unknown, use the String.charCodeAt 方法。
modifiers | Contains the list of modifier keys held down when the event occurred.

描述

A KeyDown event always occurs before a KeyPress event. If onKeyDown returns false, no KeyPress events occur. This prevents KeyPress events occurring due to the user holding down a key.

参看

onKeyPress, onKeyUp

要获得关于事件句柄的常规信息，请看“事件的常规信息”。

要获得关于事件对象的信息，请看事件。


JavaScript语言参考手册_事件和事件句柄

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

onKeyPress

 Executes JavaScript code when a KeyPress event occurs; that is, when the user presses or holds down a key.

事件适用对象 | document, Image, Link, Textarea
实现版本 | Navigator 4.0

语法

onKeyPress="handlerText"

参数

handlerTextJavaScript 代码或对一个 JavaScript 函数的调用。

使用的事件属性

type | 标明了事件的类型。
target | 标明了事件原来发送的对象。
layerX, layerY, pageX, pageY, screenX, screenY | For an event over a window, these represent the cursor location at the time the event occurred. For an event over a form, they represent the position of the form element.
which | Represents the ASCII value of the key pressed. To get the actual letter, number, or symbol of the pressed key, use the String.fromCharCode 方法。 To set this 属性 when the ASCII value is unknown, use the String.charCodeAt 方法。
modifiers | Contains the list of modifier keys held down when the event occurred.

描述

A KeyPress event occurs immediately after a KeyDown event only if onKeyDown returns something other than false. A KeyPress event repeatedly occurs until the user releases the key. You can cancel individual KeyPress events.

参看

onKeyDown, onKeyUp

要获得关于事件句柄的常规信息，请看“事件的常规信息”。

要获得关于事件对象的信息，请看事件。


JavaScript语言参考手册_事件和事件句柄

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

onKeyUp

 当 KeyUp 事件发生时执行的 JavaScript 代码。当用户释放键盘上的一个键时触发 KeyUp 事件。

事件适用对象 | document, Image, Link, Textarea
实现版本 | Navigator 4.0

语法

onKeyUp="handlerText"

参数

handlerTextJavaScript 代码或对一个 JavaScript 函数的调用。

使用的事件属性

type | 标明了事件的类型。
target | 标明了事件原来发送的对象。
layerX, layerY, pageX, pageY, screenX, screenY | 对于一个在窗口上发生的事件，这些参数表明了发生事件时鼠标指针的位置。对于一个发生在窗体上的事件，这些参数表明了窗体元素的位置。
which | 表明了按键的 ASCII 码。要获得按键实际的字母、数字或符号，可以使用 String.fromCharCode 方法。要在 ASCII 值未知的情况下设置该属性，可以使用 String.charCodeAt 方法。
modifiers | 包含了事件发生时按住的控制键清单。

参看

要获得关于事件句柄的常规信息，请看“事件的常规信息”。

要获得关于事件对象的信息，请看事件。


JavaScript语言参考手册_事件和事件句柄

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

onLoad

 Executes JavaScript code when a load event occurs; that is, when the browser finishes loading a window or all frames within a FRAMESET tag.

事件适用对象 | Image, Layer, Window
实现版本 | Navigator 2.0 Navigator 3.0: event handler of Image

语法

onLoad="handlerText"

参数

handlerTextJavaScript 代码或对一个 JavaScript 函数的调用。

描述

Use the onLoad event handler within either the BODY or the FRAMESET tag, for example, <BODY onLoad="...">.

In a FRAMESET and FRAME relationship, an onLoad event within a frame (placed in the BODY tag) occurs before an onLoad event within the FRAMESET (placed in the FRAMESET tag).

For images, the onLoad event handler indicates the script to execute when an image is displayed. Do not confuse displaying an image with loading an image. You can load several images, then display them one by one in the same Image object by setting the object's src property. If you change the image displayed in this way, onLoad executes every time an image is displayed, not just when the image is loaded into memory.

If you specify an onLoad事件适用对象an Image object that displays a looping GIF animation (multi-image GIF), each loop of the animation triggers the onLoad event, and the event handler executes once for each loop.

You can use the onLoad event handler to create a JavaScript animation by repeatedly setting the src property of an Image object. See Image for information.

使用的事件属性

type | 标明了事件的类型。
target | 标明了事件原来发送的对象。
width, height | For an event over a window, but not over a layer, these represent the width and height of the window.

示例

示例 1: Display message when page loads. In the following example, the onLoad event handler displays a greeting message after a Web page is loaded.

<BODY onLoad="window.alert("Welcome to the Brave New World home page!")> 示例 2: Display alert when image loads. The following example creates two Image objects, one with the Image constructor and one with the IMG tag. Each Image object has an onLoad event handler that calls the displayAlert function, which displays an alert. For the image created with the IMG tag, the alert displays the image name. For the image created with the Image constructor, the alert displays a message without the image name. This is because the onLoad handler for an object created with the Image constructor must be the name of a function, and it cannot specify parameters for the displayAlert function.

<SCRIPT>
imageA = new Image(50,50)
imageA.onload=displayAlert
imageA.src="cyanball.gif"
function displayAlert(theImage) {
if (theImage==null) {
alert('An image loaded')
}
else alert(theImage.name + ' has been loaded.')
}
</SCRIPT>
<IMG NAME="imageB" SRC="greenball.gif" ALIGN="top"
onLoad=displayAlert(this)><BR>
示例 3: Looping GIF animation. The following example displays an image, birdie.gif, that is a looping GIF animation. The onLoad事件适用对象the image increments the variable cycles, which keeps track of the number of times the animation has looped. To see the value of cycles, the user clicks the button labeled Count Loops.

<SCRIPT>
var cycles=0
</SCRIPT>
<IMG ALIGN="top" SRC="birdie.gif" BORDER=0
onLoad="++cycles">
<INPUT TYPE="button" VALUE="Count Loops"
onClick="alert('The animation has looped ' + cycles + ' times.')">
示例 4: Change GIF animation displayed. The following example uses an onLoad event handler to rotate the display of six GIF animations. Each animation is displayed in sequence in one Image object. When the document loads, !anim0.html is displayed. When that animation completes, the onLoad event handler causes the next file, !anim1.html, to load in place of the first file. After the last animation, !anim5.html, completes, the first file is again displayed. Notice that the changeAnimation function does not call itself after changing the src property of the Image object. This is because when the src property changes, the image's onLoad event handler is triggered and the changeAnimation function is called.

<SCRIPT>
var whichImage=0
var maxImages=5
function changeAnimation(theImage) {
++whichImage
if (whichImage <= maxImages) {
var imageName="!anim" + whichImage + ".gif"
theImage.src=imageName
} else {
whichImage=-1
return
}
}
</SCRIPT>
<IMG NAME="changingAnimation" SRC="!anim0.gif" BORDER=0 ALIGN="top"
onLoad="changeAnimation(this)">
See also示例 for  Image.

参看

onAbort, onError, onUnload

要获得关于事件句柄的常规信息，请看“事件的常规信息”。

要获得关于事件对象的信息，请看事件。


JavaScript语言参考手册_事件和事件句柄

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

onMouseDown

 当 MouseDown 事件发生时执行的 JavaScript 代码。当用户按下鼠标按钮时触发 MouseDown 事件。

事件适用对象 | Button, document, Link
实现版本 | Navigator 4.0

语法

onMouseDown="handlerText"

参数

handlerTextJavaScript 代码或对一个 JavaScript 函数的调用。

使用的事件属性

type | 标明了事件的类型。
target | 标明了事件原来发送的对象。
layerX, layerY, pageX, pageY, screenX, screenY | 表明了 MouseDown 事件发生时鼠标指针的位置。
which | Represents 1 for a left-mouse-button down and 3 for a right-mouse-button down.
modifiers | 包含了发生 MouseDown 事件时按住的控制键清单。

描述

如果 onMouseDown 返回 false 的话，缺省操作(进入拖曳模式，进入选择模式或捕获链接)将被取消。

发生在链接上的 MouseDown 将被捕获。当链接被捕获之后会改变颜色以表明状态发生了改变。

参看

要获得关于事件句柄的常规信息，请看“事件的常规信息”。

要获得关于事件对象的信息，请看事件。


JavaScript语言参考手册_事件和事件句柄

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

onMouseMove

 当发生 MouseMove 事件时执行的 JavaScript 代码；用户移动鼠标指针时触发该事件。

事件适用对象 | 无
实现版本 | Navigator 4.0

语法

onMouseMove="handlerText"

参数

handlerText JavaScript 代码或对一个 JavaScript 函数的调用。

事件归属

因为鼠标移动发生太频繁了，所以缺省情况下 onMouseMove 不是任何对象的事件。You must explicitly set it to be associated with a particular object.

使用的事件属性

type | 标明了事件的类型。
target | 标明了事件原来发送的对象。
layerX, layerY, pageX, pageY, screenX, screenY | 描述了发生 MouseMove 事件时的鼠标指针位置。

描述

仅当有对象需求捕捉时才发送 MouseMove 事件(参看“Navigator 4.0 中的事件”)。

参看

document.captureEvents

要获得关于事件句柄的常规信息，请看“事件的常规信息”。

要获得关于事件对象的信息，请看事件。


JavaScript语言参考手册_事件和事件句柄

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

onMouseOut

 当 MouseOut 事件发生时执行的 JavaScript 代码。当每次鼠标指针离开区域(客户端图像地图)或链接时触发 MouseOut 事件。

事件适用对象 | Layer, Link
实现版本 | Navigator 3.0

语法

onMouseOut="handlerText"

参数

handlerText JavaScript 代码或对一个 JavaScript 函数的调用。

描述

如果鼠标指针从客户端图像地图的一个区域移到了另外一个区域，则第一个区域会收到 onMouseOut 事件，而第二个区域会收到 onMouseOver 事件。

使用 onMouseOver 事件句柄的 Area 对象必须在 AREA 标签中使用 HREF 属性。

如果你想要在 onMouseOver 中设置 status 或 defaultStatus 的话，则必须让该事件句柄返回 true。

使用的事件属性

type | 标明了事件的类型。
target | 标明了事件原来发送的对象。
layerX, layerY, pageX, pageY, screenX, screenY | 表明了发生 MouseOut 事件时鼠标指针的位置。

示例

参看 Link 的例子。

参看

onMouseOver

要获得关于事件句柄的常规信息，请看“事件的常规信息”。

要获得关于事件对象的信息，请看事件。


JavaScript语言参考手册_事件和事件句柄

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

onMouseOver

 Executes JavaScript code when a MouseOver event occurs; that is, once each time the mouse pointer moves over an object or area from outside that object or area.

事件适用对象 | Layer, Link
实现版本 | Navigator 2.0 Navigator 3.0: event handler of Area

语法

onMouseOver="handlerText"

参数

handlerTextJavaScript 代码或对一个 JavaScript 函数的调用。

描述

If the mouse moves from one area into another in a client-side image map, you'll get onMouseOut for the first area, then onMouseOver for the second.

Area objects that use onMouseOver must include the HREF attribute within the AREA tag.

You must return true within the event handler if you want to set the status or defaultStatus properties with onMouseOver.

使用的事件属性

type | 标明了事件的类型。
target | 标明了事件原来发送的对象。
layerX, layerY, pageX, pageY, screenX, screenY | Represent the cursor location at the time the MouseOver event occurred.

示例

By default, the HREF value of an anchor displays in the status bar at the bottom of the browser when a user places the mouse pointer over the anchor. In the following example, onMouseOver provides the custom message "Click this if you dare."

<A HREF="http://home.netscape.com/"
onMouseOver="window.status='Click this if you dare!'; return true">
Click me</A> See onClick for an example of using onMouseOver when the A tag's HREF attribute is set dynamically.

See also示例 for Link.

参看

onMouseOut

要获得关于事件句柄的常规信息，请看“事件的常规信息”。

要获得关于事件对象的信息，请看事件。


JavaScript语言参考手册_事件和事件句柄

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

onMouseUp

 当 MouseUp 事件发生时执行的 JavaScript 代码。当用户释放鼠标按钮时触发 MouseUp 事件。

事件适用对象 | Button, document, Link
实现版本 | Navigator 4.0

语法

onMouseUp="handlerText"

参数

handlerTextJavaScript 代码或对一个 JavaScript 函数的调用。

使用的事件属性

type | 标明了事件的类型。
target | 标明了事件原来发送的对象。
layerX, layerY, pageX, pageY, screenX, screenY | 标明了发生 MouseUp 事件时鼠标指针的位置。
which | Represents 1 for a left-mouse-button up and 3 for a right-mouse-button up.
modifiers | 包含了发生 MouseUp 事件时按住的控制键清单。

描述

如果 onMouseUp 返回 false 的话，缺省操作将被取消。例如，如果 onMouseUp 在一个被捕获的链接上返回 false 的话，链接将不会被触发。而且，如果 MouseUp 发生在一个未被捕获的链接(也许由于 onMouseDown 返回 false)上，该链接也不会被触发。

注解

捕获是由于在链接上发生了 MouseDown。当链接被捕获之后会改变颜色以表明状态发生了改变。

参看

要获得关于事件句柄的常规信息，请看“事件的常规信息”。

要获得关于事件对象的信息，请看事件。


JavaScript语言参考手册_事件和事件句柄

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

onMove

 当 move 事件发生时执行 JavaScript 代码。当用户或者脚本移动窗口或框架时触发 move 事件。

事件适用对象 | Window
实现版本 | Navigator 4.0

语法

onMove="handlerText"

参数

handlerText JavaScript 代码或对一个 JavaScript 函数的调用。

使用的事件属性

type | 标明了事件的类型。
target | 标明了事件原来发送的对象。
screenX, screenY | 描述了窗口或框架的左上角坐标。

参看

要获得关于事件句柄的常规信息，请看“事件的常规信息”。

要获得关于事件对象的信息，请看事件。


JavaScript语言参考手册_事件和事件句柄

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

onReset

 当 reset 事件发生时执行的 JavaScript 代码。当用户重置表单(单击重置按钮)时触发 reset 事件。

事件适用对象 | Form
实现版本 | Navigator 3.0

语法

onReset="handlerText"

参数

handlerText JavaScript 代码或对一个 JavaScript 函数的调用。

示例

下面的例子显示了一个缺省值为“CA”的 Text 对象和一个重置按钮。如果用户在 Text 对象中输入了一个州的缩写并按重置按钮，则会恢复缺省值“CA”。表单的 onReset 事件句柄将显示一条信息表明已经恢复了缺省值。 <FORM NAME="form1" onReset="alert('已经恢复了缺省值。')">
州:
<INPUT TYPE="text" NAME="state" VALUE="CA" SIZE="2"><P>
<INPUT TYPE="reset" VALUE="清除表单" NAME="reset1">
</FORM>

使用的事件属性

type | 标明了事件的类型。
target | 标明了事件原来发送的对象。

参看

Form.reset, Reset

要获得关于事件句柄的常规信息，请看“事件的常规信息”。

要获得关于事件对象的信息，请看事件。


JavaScript语言参考手册_事件和事件句柄

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

onResize

 当 resize 事件发生的时候执行的 JavaScript 代码。当用户或脚本更改窗口或框架大小时触发 resize 事件。

事件适用对象 | Window
实现版本 | Navigator 4.0

语法

onResize="handlerText"

参数

handlerText JavaScript 代码或对一个 JavaScript 函数的调用。

使用的事件属性

type | 标明了事件的类型。
target | 标明了事件原来发送的对象。
width, height | 描述了窗口或框架的宽度和高度。

描述

此事件将在 HTML 布局新窗口内部尺寸完成之后触发。这将允许定位的元素和命名锚有它们最终的大小和位置序列，图像的 SRC 属性也可以动态存储，等等。

参看

要获得关于事件句柄的常规信息，请看“事件的常规信息”。

要获得关于事件对象的信息，请看事件。


JavaScript语言参考手册_事件和事件句柄

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

onSelect

 当 select 事件发生时执行 JavaScript 代码。当用户选择文本或文本区域内的某些文字时触发 select 事件。

事件适用对象 | Text, Textarea
实现版本 | Navigator 2.0

语法

onSelect="handlerText"

参数

handlerText JavaScript 代码或对一个 JavaScript 函数的调用。

使用的事件属性

type | 标明了事件的类型。
target | 标明了事件原来发送的对象。

示例

下面的例子在 valueField 文本对象中使用 onSelect 调用 selectState 函数。

<INPUT TYPE="text" VALUE="" NAME="valueField" onSelect="selectState()">

参看

要获得关于事件句柄的常规信息，请看“事件的常规信息”。

要获得关于事件对象的信息，请看事件。


JavaScript语言参考手册_事件和事件句柄

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

onSubmit

 Executes JavaScript code when a submit event occurs; that is, when a user submits a form.

事件适用对象 | Form
实现版本 | Navigator 2.0

语法

onSubmit="handlerText"

参数

handlerTextJavaScript 代码或对一个 JavaScript 函数的调用。

安全性

Navigator 4.0: Submitting a form to a mailto: or news: URL requires the UniversalSendMail privilege. 要获取 Navigator 4.0 中关于安全性更多的信息，请看“JavaScript 指南”中的第七章“JavaScript 安全性”。

描述

You can use onSubmit to prevent a form from being submitted; to do so, put a return statement that returns false in the event handler. Any other returned value lets the form submit. If you omit the return statement, the form is submitted.

使用的事件属性

type | 标明了事件的类型。
target | 标明了事件原来发送的对象。

示例

In the following example, onSubmit calls the validate function to evaluate the data being submitted. If the data is valid, the form is submitted; otherwise, the form is not submitted.

<FORM onSubmit="return validate(this)">
...
</FORM> See also the示例 for Form.

参看

Submit, Form.submit

要获得关于事件句柄的常规信息，请看“事件的常规信息”。

要获得关于事件对象的信息，请看事件。


JavaScript语言参考手册_事件和事件句柄

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

onUnload

 当 unload 事件发生时执行的 JavaScript 代码。当用户退出文档时触发 unload 事件。

事件适用对象 | Window
实现版本 | Navigator 2.0

语法

onUnload="handlerText"

参数

handlerText JavaScript 代码或对一个 JavaScript 函数的调用。

描述

onUnload 一般用在 BODY 或 FRAMESET 标签上，如<BODY onUnload="...">。

在框架集和框架关系中，单个框架的 onUnload 事件(放置在每个框架文件的 BODY 标签上)要比框架集的 onUnload 事件(放置在框架集的 FRAMESET 标签上)早发生。

使用的事件属性

type | 标明了事件的类型。
target | 标明了事件原来发送的对象。

示例

在下面的例子中，当用户退出某 Web 页时 onUnload 调用 cleanUp 函数执行某些善后操作：

<BODY onUnload="cleanUp()">

参看

onLoad

要获得关于事件句柄的常规信息，请看“事件的常规信息”。

要获得关于事件对象的信息，请看事件。

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


JavaScript语言参考手册_表单

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

第七章
表单

本章主要讲解表单的使用。所谓表单，就是在文档中出现的用于获取用户输入的部件。

表 7.1 本章用到的对象总览。

表 7.1 表单对象
对象 | 描述
Button | HTML 表单中的一个按钮。
Checkbox | HTML 表单中的一个复选框。
FileUpload | HTML 表单中的一个文件上载元素。
Form | 允许用户从像复选框、单选钮、选择列表等这样的表单元素中输入文本并做出选择。
Hidden | HTML 表单中的一个不可见文本对象。
Option | Select 对象的一个选项。
Password | HTML 表单中的一个文本域，其中的值以星号(*)显示。
Radio | HTML 表单中的一组单选钮。
Reset | HTML 表单中的一个重置按钮。
Select | HTML 表单中的一个选择列表。
Submit | HTML 表单中的一个提交按钮。
Text | HTML 表单中的一个文本输入域。
Textarea | HTML 表单中的一个多行输入域。

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


JavaScript语言参考手册_表单

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

Form

 Lets users input text and make choices from Form elements such as checkboxes, radio buttons, and selection lists. You can also use a form to post data to a server.

客户端对象 |
实现版本 | Navigator 2.0 Navigator 3.0: 添加了 reset 方法。 Navigator 4.0: 添加了 handleEvent 方法。

创建源

The HTML FORM tag. The JavaScript runtime engine creates a Form object for each FORM tag in the document. You access FORM objects through the document.forms property and through named properties of that object.

To define a form, use standard HTML语法 with the addition of JavaScript event handlers. If you supply a value for the NAME attribute, you can use that value to index into the forms array. In addition, the associated document object has a named property for each named form.

事件句柄

  • onReset
  • onSubmit

描述

 Each form in a document is a distinct object. You can refer to a form's elements in your code by using the element's name (from the NAME attribute) or the Form.elements array. The elements array contains an entry for each element (such as a Checkbox, Radio, or Text object) in a form.

If multiple objects on the same form have the same NAME attribute, an array of the given name is created automatically. Each element in the array represents an individual Form object. Elements are indexed in source order starting at 0. For example, if two Text elements and a Textarea element on the same form have their NAME attribute set to "myField", an array with the elements myField[0], myField[1], and myField[2] is created. You need to be aware of this situation in your code and know whether myField refers to a single element or to an array of elements.

属性概览

action | Reflects the ACTION attribute.
elements | An array reflecting all the elements in a form.
encoding | Reflects the ENCTYPE attribute.
length | Reflects the number of elements on a form.
方法 | Reflects the METHOD attribute.
name | Reflects the NAME attribute.
target | Reflects the TARGET attribute.

方法概览

handleEvent | 调用指定事件的控制句柄。
reset | Simulates a mouse click on a reset button for the calling form.
submit | Submits a form.

示例

 示例 1: Named form. The following example creates a form called myForm that contains text fields for first name and last name. The form also contains two buttons that change the names to all uppercase or all lowercase. The function setCase shows how to refer to the form by its name.

<HTML>
<HEAD>
<TITLE>Form object example</TITLE>
</HEAD>
<SCRIPT>
function setCase (caseSpec){
if (caseSpec == "upper") {
document.myForm.firstName.value=document.myForm.firstName.value.toUpperCase()
document.myForm.lastName.value=document.myForm.lastName.value.toUpperCase()}
else {
document.myForm.firstName.value=document.myForm.firstName.value.toLowerCase()
document.myForm.lastName.value=document.myForm.lastName.value.toLowerCase()}
}
</SCRIPT> <BODY>
<FORM NAME="myForm">
<B>First name:</B>
<INPUT TYPE="text" NAME="firstName" SIZE=20>
<BR><B>Last name:</B>
<INPUT TYPE="text" NAME="lastName" SIZE=20>
<P><INPUT TYPE="button" VALUE="Names to uppercase" NAME="upperButton"
onClick="setCase('upper')">
<INPUT TYPE="button" VALUE="Names to lowercase" NAME="lowerButton"
onClick="setCase('lower')">
</FORM>
</BODY>
</HTML> 示例 2: forms array. The onLoad event handler in the following example displays the name of the first form in an Alert dialog box.

<BODY onLoad="alert('You are looking at the ' + document.forms[0] + ' form!')"> If the form name is musicType, the alert displays the following message:

You are looking at the <object musicType> form! 示例 3: onSubmit event handler. The following example shows an onSubmit event handler that determines whether to submit a form. The form contains one Text object where the user enters three characters. onSubmit calls a function, checkData, that returns true if there are 3 characters; otherwise, it returns false. Notice that the form's onSubmit event handler, not the submit button's onClick event handler, calls the checkData function. Also, onSubmit contains a return statement that returns the value obtained with the function call.

<HTML>
<HEAD>
<TITLE>Form object/onSubmit event handler example</TITLE>
<TITLE>Form object example</TITLE>
</HEAD>
<SCRIPT>
var dataOK=false
function checkData (){
if (document.myForm.threeChar.value.length == 3) {
return true}
else {
alert("Enter exactly three characters. " + document.myForm.threeChar.value +
" is not valid.")
return false}
}
</SCRIPT>
<BODY>
<FORM NAME="myForm" onSubmit="return checkData()">
<B>Enter 3 characters:</B>
<INPUT TYPE="text" NAME="threeChar" SIZE=3>
<P><INPUT TYPE="submit" VALUE="Done" NAME="submit1"
onClick="document.myForm.threeChar.value=document.myForm.threeChar.value.toUpperCase()">
</FORM>
</BODY>
</HTML> 示例 4: submit method. The following example is similar to the previous one, except it submits the form using the submit method instead of a Submit object. The form's onSubmit event handler does not prevent the form from being submitted. The form uses a button's onClick event handler to call the checkData function. If the value is valid, the checkData function submits the form by calling the form's submit method.

<HTML>
<HEAD>
<TITLE>Form object/submit method example</TITLE>
</HEAD>
<SCRIPT>
var dataOK=false
function checkData (){
if (document.myForm.threeChar.value.length == 3) {
document.myForm.submit()}
else {
alert("Enter exactly three characters. " + document.myForm.threeChar.value +
" is not valid.")
return false}
}
</SCRIPT>
<BODY>
<FORM NAME="myForm" onSubmit="alert('Form is being submitted.')">
<B>Enter 3 characters:</B>
<INPUT TYPE="text" NAME="threeChar" SIZE=3>
<P><INPUT TYPE="button" VALUE="Done" NAME="button1"
onClick="checkData()">
</FORM>
</BODY>
</HTML>

参看

Button, Checkbox, FileUpload, Hidden, Password, Radio, Reset, Select, Submit, Text, Textarea.

属性

action

 A string specifying a destination URL for form data that is submitted

属性源 | Form
实现版本 | Navigator 2.0

安全性

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

Navigator 4.0: Submitting a form to a mailto: or news: URL requires the UniversalSendMail privilege. 要获取 Navigator 4.0 中关于安全性更多的信息，请看“JavaScript 指南”中的第七章“JavaScript 安全性”。

描述

The action property is a reflection of the ACTION attribute of the FORM tag. Each section of a URL contains different information. See Location for a描述 of the URL components.

示例

The following example sets the action property of the musicForm form to the value of the variable urlName:

document.musicForm.action=urlName

参看

Form.encoding, Form.method, Form.target

elements

An array of objects corresponding to form elements (such as checkbox, radio, and Text objects) in source order.

属性源 | Form
只读 |
实现版本 | Navigator 2.0

描述

You can refer to a form's elements in your code by using the elements array. This array contains an entry for each object (Button, Checkbox, FileUpload, Hidden, Password, Radio, Reset, Select, Submit, Text, or Textarea object) in a form in source order. Each radio button in a Radio object appears as a separate element in the elements array. For example, if a form called myForm has a text field and two checkboxes, you can refer to these elements myForm.elements[0], myForm.elements[1], and myForm.elements[2].

Although you can also refer to a form's elements by using the element's name (from the NAME attribute), the elements array provides a way to refer to Form objects programmatically without using their names. For example, if the first object on the userInfo form is the userName Text object, you can evaluate it in either of the following ways:

userInfo.userName.value
userInfo.elements[0].value The value of each element in the elements array is the full HTML statement for the object.

示例

See the示例 for Frame.

encoding

A string specifying the MIME encoding of the form.

属性源 | Form
实现版本 | Navigator 2.0

描述

The encoding property initially reflects the ENCTYPE attribute of the FORM tag; however, setting encoding overrides the ENCTYPE attribute.

示例

The following function returns the value of the encoding property of musicForm:

function getEncoding() {
return document.musicForm.encoding
}

参看

Form.action, Form.method, Form.target

length

The number of elements in the form.

属性源 | Form
只读 |
实现版本 | Navigator 2.0

描述

The form.length property tells you how many elements are in the form. You can get the same information using form.elements.length.

method

A string specifying how form field input information is sent to the server.

属性源 | Form
实现版本 | Navigator 2.0

描述

The method property is a reflection of the METHOD attribute of the FORM tag. The method property should evaluate to either "get" or "post".

示例

The following function returns the value of the musicForm method property:

function getMethod() {
return document.musicForm.method
}

参看

Form.action, Form.encoding, Form.target

name

A string specifying the name of the form.

属性源 | Form
实现版本 | Navigator 2.0

安全性

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

描述

The name property initially reflects the value of the NAME attribute. Changing the name property overrides this setting.

示例

In the following example, the valueGetter function uses a for loop to iterate over the array of elements on the valueTest form. The msgWindow window displays the names of all the elements on the form:

newWindow=window.open("http://home.netscape.com")
function valueGetter() {
var msgWindow=window.open("")
for (var i = 0; i < newWindow.document.valueTest.elements.length; i++) {
msgWindow.document.write(newWindow.document.valueTest.elements[i].name + "<BR>")
}
}

target

A string specifying the name of the window that responses go to after a form has been submitted.

属性源 | Form
实现版本 | Navigator 2.0

描述

The target property initially reflects the TARGET attribute of the A, AREA, and FORM tags; however, setting target overrides these attributes.

You can set target using a string, if the string represents a window name. The target property cannot be assigned the value of a JavaScript expression or variable.

示例

The following example specifies that responses to the musicInfo form are displayed in the msgWindow window:

document.musicInfo.target="msgWindow"

参看

Form.action, Form.encoding, Form.method

方法

handleEvent

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

方法源 | Form
实现版本 | Navigator 4.0

语法

handleEvent(event)

参数

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

描述

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

reset

Simulates a mouse click on a reset button for the calling form.

方法源 | Form
实现版本 | Navigator 3.0

语法

reset()

参数

 无

描述

The reset method restores a form element's default values. A reset button does not need to be defined for the form.

示例

The following example displays a Text object in which the user is to type "CA" or "AZ". The Text object's onChange event handler calls a function that executes the form's reset method if the user provides incorrect input. When the reset method executes, defaults are restored and the form's onReset event handler displays a message.

<SCRIPT>
function verifyInput(textObject) {
if (textObject.value == 'CA' || textObject.value == 'AZ') {
alert('Nice input')
}
else { document.myForm.reset() }
}
</SCRIPT>
<FORM NAME="myForm" onReset="alert('Please enter CA or AZ.')">
Enter CA or AZ:
<INPUT TYPE="text" NAME="state" SIZE="2" onChange=verifyInput(this)><P>
</FORM>

参看

onReset, Reset

submit

Submits a form.

方法源 | Form
实现版本 | Navigator 2.0

语法

submit()

参数

 无

安全性

Navigator 3.0: The submit method fails without notice if the form's action is a mailto:, news:, or snews: URL. Users can submit forms with such URLs by clicking a submit button, but a confirming dialog will tell them that they are about to give away private or sensitive information.

Navigator 4.0: Submitting a form to a mailto: or news: URL requires the UniversalSendMail privilege. 要获取 Navigator 4.0 中关于安全性更多的信息，请看“JavaScript 指南”中的第七章“JavaScript 安全性”。

描述

The submit method submits the specified form. It performs the same action as a submit button.

Use the submit method to send data back to an HTTP server. The submit method returns the data using either "get" or "post," as specified in Form.method.

示例

The following example submits a form called musicChoice:

document.musicChoice.submit() If musicChoice is the first form created, you also can submit it as follows:

document.forms[0].submit() See also the example for Form.

参看

Submit, onSubmit


JavaScript语言参考手册_表单

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

Hidden

 A Text object that is suppressed from form display on an HTML form. A Hidden object is used for passing name/value pairs when a form submits.

客户端对象 |
实现版本 | Navigator 2.0 Navigator 3.0: 添加了 type 属性

创建源

The HTML INPUT tag, with "hidden" as the value of the TYPE attribute. For a given form, the JavaScript runtime engine creates appropriate Hidden objects and puts these objects in the elements array of the corresponding Form object. You access a Hidden object by indexing this array. You can index the array either by number or, if supplied, by using the value of the NAME attribute.

描述

A Hidden object is a form element and must be defined within a FORM tag.

A Hidden object cannot be seen or modified by an end user, but you can programmatically change the value of the object by changing its value property. You can use Hidden objects for client/server communication.

属性概览

form | Specifies the form containing the Hidden object.
name | Reflects the NAME attribute.
type | Reflects the TYPE attribute.
value | Reflects the current value of the Hidden object.

示例

The following example uses a Hidden object to store the value of the last object the user clicked. The form contains a "Display hidden value" button that the user can click to display the value of the Hidden object in an Alert dialog box.

<HTML>
<HEAD>
<TITLE>Hidden object example</TITLE>
</HEAD>
<BODY>
<B>Click some of these objects, then click the "Display value" button
<BR>to see the value of the last object clicked.</B>
<FORM NAME="myForm">
<INPUT TYPE="hidden" NAME="hiddenObject" VALUE="无">
<P>
<INPUT TYPE="button" VALUE="Click me" NAME="button1"
onClick="document.myForm.hiddenObject.value=this.value">
<P>
<INPUT TYPE="radio" NAME="musicChoice" VALUE="soul-and-r&b"
onClick="document.myForm.hiddenObject.value=this.value"> Soul and R&B
<INPUT TYPE="radio" NAME="musicChoice" VALUE="jazz"
onClick="document.myForm.hiddenObject.value=this.value"> Jazz
<INPUT TYPE="radio" NAME="musicChoice" VALUE="classical"
onClick="document.myForm.hiddenObject.value=this.value"> Classical
<P>
<SELECT NAME="music_type_single"
onFocus="document.myForm.hiddenObject.value=this.options[this.selectedIndex].text">
<OPTION SELECTED> Red <OPTION> Orange <OPTION> Yellow
</SELECT>
<P><INPUT TYPE="button" VALUE="Display hidden value" NAME="button2"
onClick="alert('Last object clicked: ' + document.myForm.hiddenObject.value)">
</FORM>
</BODY>
</HTML>

参看

document.cookie

属性

form

 An object reference specifying the form containing this object.

方法源 | Hidden
只读 |
实现版本 | Navigator 2.0

描述

每个表单元素都有一个 form 属性用于指向元素的父表单。该属性在事件控制句柄中特别有用，你可能想要由其获得当前表单中其它元素。

示例

示例 1. In the following example, the form myForm contains a Hidden object and a button. When the user clicks the button, the value of the Hidden object is set to the form's name. The button's onClick event handler uses this.form to refer to the parent form, myForm.

<FORM NAME="myForm">
Form name:<INPUT TYPE="hidden" NAME="h1" VALUE="Beluga">
<P>
<INPUT NAME="button1" TYPE="button" VALUE="Store Form Name"
onClick="this.form.h1.value=this.form.name">
</FORM> 示例 2. The following example uses an object reference, rather than the this keyword, to refer to a form. The code returns a reference to myForm, which is a form containing myHiddenObject.

document.myForm.myHiddenObject.form

参看

Form

name

A string specifying the name of this object.

方法源 | Hidden
实现版本 | Navigator 2.0

安全性

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

type

For all Hidden objects, the value of the type property is "hidden". This property specifies the form element's type.

方法源 | Hidden
只读 |
实现版本 | Navigator 3.0

示例

The following example writes the value of the type property for every element on a form.

for (var i = 0; i < document.myForm.elements.length; i++) {
document.writeln("<BR>type is " + document.myForm.elements[i].type)
}

value

A string that reflects the VALUE attribute of the object.

方法源 | Hidden
实现版本 | Navigator 2.0

安全性

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

示例

The following function evaluates the value property of a group of buttons and displays it in the msgWindow window:

function valueGetter() {
var msgWindow=window.open("")
msgWindow.document.write("The submit button says " +
document.valueTest.submitButton.value + "<BR>")
msgWindow.document.write("The reset button says " +
document.valueTest.resetButton.value + "<BR>")
msgWindow.document.write("The hidden field says " +
document.valueTest.hiddenField.value + "<BR>")
msgWindow.document.close()
} This example displays the following values:

The submit button says Query Submit
The reset button says Reset
The hidden field says pipefish are cute. The previous example assumes the buttons have been defined as follows:

<INPUT TYPE="submit" NAME="submitButton">
<INPUT TYPE="reset" NAME="resetButton">
<INPUT TYPE="hidden" NAME="hiddenField" VALUE="pipefish are cute.">


JavaScript语言参考手册_全局函数

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

第十三章
全局函数

本章包含了 JavaScript 所有不与任何对象关联的函数。

表 13.1 总览了这些函数。

表 13.1 全局函数
函数 | 描述
addClient | Appends client information to URLs.
addResponseHeader | Adds new information to the response header sent to the client.
blob | Assigns BLOb data to a column in a cursor.
callC | Calls a native function.
debug | Displays values of expressions in the trace window or frame.
deleteResponseHeader | Removes information from the header of the response sent to the client.
escape | Returns the hexadecimal encoding of an argument in the ISO Latin-1 character set; used to create strings to add to a URL.
eval | Evaluates a string of JavaScript code without reference to a particular object.
flush | Flushes the output buffer.
getOptionValue | Gets values of individual options in an HTML SELECT form element.
getOptionValueCount | Gets the number of options in an HTML SELECT form element.
isNaN | Evaluates an argument to determine if it is not a number.
Number | Converts an object to a number.
parseFloat | Parses a string argument and returns a floating-point number.
parseInt | Parses a string argument and returns an integer.
redirect | Redirects the client to the specified URL.
registerCFunction | Registers a native function for use in server-side JavaScript.
ssjs_generateClientID | Returns an identifier you can use to uniquely specify the client object.
ssjs_getCGIVariable | Returns the value of the specified environment variable set in the server process, including some CGI variables.
ssjs_getClientID | Returns the identifier for the client object used by some of JavaScript's client-maintenance techniques.
String | Converts an object to a string.
taint | Adds tainting to a data element or script.
unescape | Returns the ASCII string for the specified value; used in parsing a string 添加了 to a URL.
untaint | Removes tainting from a data element or script.
write | Adds statements to the client-side HTML page being generated.

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


JavaScript语言参考手册_全局函数

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

addClient

 将客户对象属性值添加到动态生成的 URL 或用重定向功能实现的 URL。

服务器端函数 |
实现版本 | LiveWire 1.0

语法

addClient(URL)

参数

URL 描述 URL 的字符串。

描述

addClient 函数是一个顶级的服务器端 JavaScript 函数，并不与任何对象关联。

使用 addClient 可以当你使用重定向或生成的动态链接时保留客户对象属性值。如果应用程序使用客户或服务器 URL 编码维护客户对象则此内容十分必要；它并没有其它方面的负面影响。因为客户维护技术可以在应用程序编译后被更改，所以使用 addClient 函数总是十分安全的，甚至你并没有计划使用 URL 编码技术。

关于使用 URL 编码维护客户属性的内容，请看编写服务器端 JavaScript 应用程序。

示例

在下面的例子中，使用了 addClient 和 redirect 函数用于重定向浏览器：

redirect(addClient("mypage.html"))

在下面的例子中，addClient 在动态生成链接时保留了客户对象属性值：

<A HREF='addClient("page" + project.pageno + ".html")'>跳转到其它页</A>

参看

redirect


JavaScript语言参考手册_全局函数

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

addResponseHeader

 向发送给客户的回应头添加新信息。

服务器端函数 |
实现版本 | Netscape Server 3.0

语法

addResponseHeader(field, value)

参数

field | 要添加到回应头的域。
value | 为该域指定的信息。

描述

你可以使用 addResponseHeader 函数向你发送到客户的回应头中添加信息。

例如，如果你发送到客户端的回应使用了自定义的内容类型，你就应该将此内容类型编码在回应头中。JavaScript 运行时刻引擎将会向回应头中自动添加缺省的内容类型(text/html)。如果你使用了自定义的头，你就必须先从头中删除缺省的内容类型，再添加新的。如果你的回应使用 royalairways-format 作为自定义内容类型，你就可以这么指定它：

deleteResponseHeader("content-type");
addResponseHeader("content-type","royalairways-format");

你可以使用 addResponseHeader 函数添加任何其它你想要添加到回应头中的信息。

请记住头将作为回应的第一部分发送。因此，你就应该在每页较早脚本中调用这些函数。实际上，你必须保证回应头已经在下列事件发生之前设置好了：

  • 运行时刻引擎生成 HTML 页的前 64KB(此时它会自动将输出写到客户端并清空缓冲区)。

  • 你调用 flush 函数清空输出缓冲区。

  • 你调用 redirect 函数更改客户端的需求。

参看

 deleteResponseHeader


JavaScript语言参考手册_全局函数

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

blob

 给表中的列赋 BLOb 数据。

服务器端函数 |
实现版本 | LiveWire 1.0

语法

blob (path)

参数

path 一个字符串，表明了包含有 BLOb 数据的文件名。该字符串必须是绝对路径。

返回

一个 blob 对象。

描述

和可更新的表一起使用此函数可以插入或更新包含 BLOb 数据的一行。要使用 SQL 的 execute 方法插入或更新一行，请使用你的数据库供应商支持的语法。

在 DB2 中，blobs 限制最多为 32 千字节。

请记住，反斜线(“\”)是 JavaScript 重的转义字符。由此原因，在 NT 的文件名中你就必须使用两个反斜线或正斜线。

示例

下面的语句用从指定的 GIF 文件中获取的 BLOb 数据更新了 EMPLOYEE 表中当前行上的 PHOTO 和 OFFICE 列。

// 创建一个临时表
cursor = database.cursor("SELECT * FROM customer WHERE //原文如此，本人无法修改(译者注)
customer.ID = " + request.customerID
// 定位行指针
cursor.next()
// 赋 blob 数据
cursor.photo = blob("c:/customer/photos/myphoto.gif")
cursor.office = blob("c:/customer/photos/myoffice.gif")
// 并且更新行
cursor.updateRow("employee")


JavaScript语言参考手册_全局函数

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

callC

 调用一个外部函数并返回该外部函数的返回值。

服务器端函数 |
实现版本 | LiveWire 1.0

语法

callC(JSFunctionName, arg1,..., argN)

参数

JSFunctionName | 用 RegisterCFunction 标识的函数名称。
arg1...argN | 用逗号分隔的外部函数参数清单。参数可以是任何 JavaScript 值：字符串、数值或布尔值。参数的个数必须与外部函数需要的参数个数相同。

描述

callC 是一个顶级服务器端 JavaScript 函数，并不与任何对象关联。

callC 函数将返回外部函数返回的字符串值；callC 只能返回字符串值。

示例

下面的例子根据注册外部函数 echoCCallArguments 是否成功给变量 isRegistered 赋值。如果 isRegistered 为 true 的话，将执行 callC 函数。

var isRegistered =
registerCFunction("echoCCallArguments",
"c:/mypath/mystuff.dll",
"mystuff_EchoCCallArguments")
if (isRegistered == true) {
var returnValue =
callC("echoCCallArguments", "first arg", 42, true, "last arg")
write(returnValue)
}

参看

registerCFunction


JavaScript语言参考手册_全局函数

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

debug

 在跟踪工具中显示一个 JavaScript 表达式。

服务器端函数 |
实现版本 | LiveWire 1.0

语法

debug(expression)

参数

expression 任意合法的 JavaScript 表达式。

描述

debug 函数是一个顶级的服务器端 JavaScript 函数，并不与任何对象关联。

使用此函数可以显示一个用于调试目的的表达式的值。该值将在应用程序管理器的跟踪工具中出现，前面有一个“Debug message:”的简要描述。

示例

下面的例子将显示变量的值：

debug("data 变量的最终值是 " + data)


JavaScript语言参考手册_全局函数

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

deleteResponseHeader

 从发送到客户端的回应头中删除信息。

服务器端函数 |
实现版本 | Netscape Server 3.0

语法

deleteResponseHeader(field)

参数

field 要从回应头中删除的域。

描述

你可以使用 deleteResponseHeader 函数从你发送到客户端的回应头中删除信息。该函数最常见的用途是在用 addResponseHeader 添加你自己的内容类型信息之前删除缺省的内容类型信息。

有关更多信息，请看 addResponseHeader。


JavaScript语言参考手册_全局函数

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

escape

 返回以 ISO-Latin-1 字符集书写的参数的十六进制编码。

核心函数 |
实现版本 | Navigator 2.0, LiveWire 1.0

语法

escape("string")

参数

string 以 ISO-Latin-1 字符集书写的字符串。

描述

escape 函数是一个顶级 JavaScript 函数，并不与任何对象关联。使用 escape 和 unescape 函数可以将属性值手工添加到 URL 中。

escape 函数编码指定字符串中的特定字符，并返回新字符串。它编码空格、标点符号及其它不位于 ASCII 字母表的字符，除了以下字符：

* @ - _ + . /

示例

示例 1. 下面的例子返回 "%26"：

escape("&")

示例 2. 该语句

escape("The_rain. In Spain, Ma'am") 返回

"The_rain.%20In%20Spain%2C%20Ma%92am":

示例 3. 在下面的例子中，如果用户单击链接的话，变量 theValue 的值将被以十六进制字符串编码并被传送给 request 对象：

<A HREF=\Q"mypage.html?val1="+escape(theValue)\Q)>Click Here</A>

参看

unescape


JavaScript语言参考手册_全局函数

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

eval

 Evaluates a string of JavaScript code without reference to a particular object.

核心函数 |
实现版本 | Navigator 2.0

语法

eval(string)

参数

stringA string representing a JavaScript expression, statement, or sequence of statements. The expression can include variables and properties of existing objects.

描述

The argument of the eval function is a string. If the string represents an expression, eval evaluates the expression. If the argument represents one or more JavaScript statements, eval performs the statements. Do not call eval to evaluate an arithmetic expression; JavaScript evaluates arithmetic expressions automatically.

If you construct an arithmetic expression as a string, you can use eval to evaluate it at a later time. For example, suppose you have a variable x. You can postpone evaluation of an expression involving x by assigning the string value of the expression, say "3 * x + 2", to a variable, and then calling eval at a later point in your script.

eval is also a method of all objects. This method is described for the Object class.

示例

The following示例 display output using document.write. In server-side JavaScript, you can display the same output by calling the write function instead of using document.write.

示例 1. Both of the write statements below display 42. The first evaluates the string "x + y + 1"; the second evaluates the string "42".

var x = 2
var y = 39
var z = "42"
document.write(eval("x + y + 1"), "<BR>")
document.write(eval(z), "<BR>")
示例 2. In the following example, the getFieldName(n) function returns the name of the specified form element as a string. The first statement assigns the string value of the third form element to the variable field. The second statement uses eval to display the value of the form element.

var field = getFieldName(3)
document.write("The field named ", field, " has value of ",
eval(field + ".value")) 示例 3. The following example uses eval to evaluate the string str. This string consists of JavaScript statements that open an Alert dialog box and assign z a value of 42 if x is five, and assigns 0 to z otherwise. When the second statement is executed, eval will cause these statements to be performed, and it will also evaluate the set of statements and return the value that is assigned to z.

var str = "if (x == 5) {alert('z is 42'); z = 42;} else z = 0; "
document.write("<P>z is ", eval(str)) 示例 4. In the following example, the setValue function uses eval to assign the value of the variable newValue to the text field textObject:

function setValue (textObject, newValue) {
eval ("document.forms[0]." + textObject + ".value") = newValue
} 示例 5. The following example creates breed as a property of the object myDog, and also as a variable. The first write statement uses eval('breed') without specifying an object; the string "breed" is evaluated without regard to any object, and the write method displays "Shepherd", which is the value of the breed variable. The second write statement uses myDog.eval('breed') which specifies the object myDog; the string "breed" is evaluated with regard to the myDog object, and the write method displays "Lab", which is the value of the breed property of the myDog object.

function Dog(name,breed,color) {
this.name=name
this.breed=breed
this.color=color
}
myDog = new Dog("Gabby")
myDog.breed="Lab"
var breed='Shepherd'
document.write("<P>" + eval('breed'))
document.write("<BR>" + myDog.eval('breed'))

参看

Object.eval method


JavaScript语言参考手册_全局函数

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

flush

 将数据从内部缓冲区发送到客户端。

服务器端函数 |
实现版本 | LiveWire 1.0

语法

flush()

参数

 无。

描述

为了改善性能，JavaScript 将缓冲它生成的 HTML 页。flush 函数立即将数据从内部缓冲区发送到客户端。如果你不强制调用 flush 函数，JavaScript 将在数据每够 64KB 之后将其发送到客户端生成的 HTML 页。

使用 flush 函数可以控制何时将数据发送到客户端。例如，在进行会有延迟的操作(如数据库查询)前调用 flush 函数。如果数据库查询将获得大量的行，你就可以在收到一小部分行时清空缓冲区以免显示数据的长时间等待。

因为 flush 函数将作为 HTTP 头的一部分更新客户端的 cookie 文件，你应该在执行该函数之前执行任何对客户端对象的修改，如果你使用客户端的 cookie 维护客户对象的话。要获得关于此内容的更多信息，请参看编写服务器端 JavaScript 应用程序。请不要将此顶级 JavaScript 函数与 File 对象的 flush 方法混淆。flush 是一个顶级的服务器端 JavaScript 函数，并不与任何对象关联。

示例

下面的例子将逐行读入文本文件的内容，并将其内容输出，前面带有行号及五个空格。flush 函数将导致客户端显示输出结果。

while (!In.eof()) {
AscLine = In.readln();
if (!In.eof())
write(LPad(LineCount + ": ", 5), AscLine, "\n");
LineCount++;
flush();
}

参看

write


JavaScript语言参考手册_全局函数

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

getOptionValue

 Returns the text of a selected OPTION in a SELECT form element.

服务器端函数 |
实现版本 | LiveWire 1.0

语法

getOptionValue(name, index)

参数

name | A name specified by the NAME attribute of the SELECT tag
index | Zero-based ordinal index of the selected option.

返回

A string containing the text for the selected option, as specified by the associated OPTION tag.

描述

The getOptionValue 函数是一个顶级的服务器端 JavaScript 函数，并不与任何对象关联。 It corresponds to the Option.text property available to client-side JavaScript.

The SELECT tag allows multiple values to be associated with a single form element, with the MULTIPLE attribute. If your application requires select lists that allow multiple selected options, you use the getOptionValue function to get the values of selected options in server-side JavaScript.

示例

Suppose you have the following form element:

<SELECT NAME="what-to-wear" MULTIPLE SIZE=8>
<OPTION SELECTED>Jeans
<OPTION>Wool Sweater
<OPTION SELECTED>Sweatshirt
<OPTION SELECTED>Socks
<OPTION>Leather Jacket
<OPTION>Boots
<OPTION>Running Shoes
<OPTION>Cape
</SELECT> You could process the input from this select list in server-side JavaScript as follows:

<SERVER>
var loopIndex = 0
var loopCount = getOptionValueCount("what-to-wear") // 3 by default
while ( loopIndex < loopCount ) {
var optionValue = getOptionValue("what-to-wear",loopIndex)
write("<br>Item #" + loopIndex + ": " + optionValue + "\n")
loopIndex++
}
</SERVER> If the user kept the default selections, this script would return

Item #1: Jeans
Item #3: Sweatshirt
Item #4: Socks

参看

getOptionValueCount


JavaScript语言参考手册_全局函数

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

getOptionValueCount

 获得 SELECT 表单元素中用户选中的选项数目。

服务器端函数 |
实现版本 | LiveWire 1.0

语法

getOptionValueCount(name)

参数

name 指定 SELECT 标签中的 NAME 属性。

描述

getOptionValueCount 函数是一个顶级的服务器端 JavaScript 函数，并不与任何对象关联。

与 getOptionValue 一起使用此函数可以处理允许多个选择项的 SELECT 表单元素。

示例

参看 getOptionValue 的例子。

参看

getOptionValue


JavaScript语言参考手册_全局函数

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

isNaN

 计算一个参数，检查它是否为数值。

核心函数 |
实现版本 | Navigator 2.0: 仅在 Unix上 Navigator 3.0, LiveWire 1.0: 所有平台

语法

isNaN(testValue)

参数

testValue 你想要测试的值。

描述

isNaN 是一个内建的 JavaScript 函数。它并不是与任何对象关联的方法，而仅仅是语言的一部分。

在支持 NaN 的平台上，parseFloat 和 parseInt 函数将在计算并不是数值的值时返回“NaN”。isNaN 在传递过来的参数是“NaN”时返回真，否则返回假。

示例

下面的例子计算 floatValue，确定它是否为数值，以便调用相应的过程：

floatValue=parseFloat(toFloat)
if (isNaN(floatValue)) {
notFloat()
} else {
isFloat()
}

参看

Number.NaN, parseFloat, parseInt


JavaScript语言参考手册_全局函数

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

Number

 将指定对象转换为数字。

核心函数 |
实现版本 | Navigator 4.0, Netscape Server 3.0

语法

Number(obj)

参数

obj 一个对象。

描述

如果对象是 Date 类型的对象，Number 将返回自格林威治标准时间 1970 年 1 月 1 日起已经经过的毫秒数，在此日期之后的是正数，之前的是负数。

如果 obj 是一个没有数字格式的字符串，Number 将返回 NaN。

示例

下面的例子将把 Date 对象转换为数值型值：

<SCRIPT>
d = new Date ("December 17, 1995 03:24:00");
document.write (Number(d) + "<BR>");
</SCRIPT> 屏幕上将显示 "819199440000."

参看

Number

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

回页面顶部 回页面顶部


JavaScript语言参考手册_全局函数

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

parseFloat

 处理字符串参数，将其以浮点数的形式返回。

核心函数 |
实现版本 | Navigator 2.0: 如果在 parseFloat(string) 中指定的字符串的第一个字符不能转换为数值的话，则在 Solaris 和 Irix 上返回“NaN”，在其它平台上返回 0。 Navigator 3.0, LiveWire 1.0: 在上述情况下，所有平台均会返回“NaN”。

语法

parseFloat(string)

参数

string 表示了你想要处理的字符串的值。

描述

parseFloat 函数是一个内置的 JavaScript 函数。

parseFloat 将把其参数，一个字符串，处理后返回浮点数值。如果遇到了不是符号(+或-)，不是数码(0-9)，不是小数点，也不是指数的字符，就会停止处理，忽略该字符及其以后的所有字符。

如果第一个字符就不能转换为数值，parseFloat 将返回“NaN”。

仅就数学运算目的而言，“NaN”一点用也没有，当然也不应该参加运算。你可以调用 isNaN 函数来判断 parseFloat 的返回值是否为“NaN”。如果将“NaN”传递给数学运算符，那么运算的结果也是“NaN”。

示例

下面的例子都将返回 3.14：

parseFloat("3.14")
parseFloat("314e-2")
parseFloat("0.0314E+2")
var x = "3.14"
parseFloat(x)

下面的例子将返回“NaN”：

parseFloat("FF2")

参看

isNaN, parseInt


JavaScript语言参考手册_全局函数

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

parseInt

 Parses a string argument and returns an integer of the specified radix or base.

核心函数 |
实现版本 | Navigator 2.0: If the first character of the string specified in parseInt(string) cannot be converted to a number, returns "NaN" on Solaris and Irix and 0 on all other platforms.Navigator 3.0, LiveWire 2.0: Returns "NaN" on all platforms if the first character of the string specified in parseInt(string) cannot be converted to a number.

语法

parseInt(string,radix)

参数

string | A string that represents the value you want to parse.
radix | (Optional) An integer that represents the radix of the return value.

描述

The parseInt function is a built-in JavaScript function.

The parseInt function parses its first argument, a string, and attempts to return an integer of the specified radix (base). For example, a radix of 10 indicates to convert to a decimal number, 8 octal, 16 hexadecimal, and so on. For radixes above 10, the letters of the alphabet indicate numerals greater than 9. For example, for hexadecimal numbers (base 16), A through F are used.

If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point. parseInt truncates numbers to integer values.

If the radix is not specified or is specified as 0, JavaScript assumes the following:

  • If the input string begins with "0x", the radix is 16 (hexadecimal).

  • If the input string begins with "0", the radix is eight (octal).

  • If the input string begins with any other value, the radix is 10 (decimal).
If the first character cannot be converted to a number, parseInt returns "NaN".

For arithmetic purposes, the "NaN" value is not a number in any radix. You can call the isNaN function to determine if the result of parseInt is "NaN". If "NaN" is passed on to arithmetic operations, the operation results will also be "NaN".

示例

The following示例 all return 15:

parseInt("F", 16)
parseInt("17", 8)
parseInt("15", 10)
parseInt(15.99, 10)
parseInt("FXX123", 16)
parseInt("1111", 2)
parseInt("15*3", 10)
The following示例 all return "NaN":

parseInt("Hello", 8)
parseInt("0x7", 10)
parseInt("FFF", 10)
Even though the radix is specified differently, the following示例 all return 17 because the input string begins with "0x".

parseInt("0x11", 16)
parseInt("0x11", 0)
parseInt("0x11")

参看

isNaN, parseFloat, Object.valueOf


JavaScript语言参考手册_全局函数

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

redirect

 重定义客户到指定的 URL。

服务器端函数 |
实现版本 | LiveWire 1.0

语法

redirect(location)

参数

location 你想要将客户重定向到的 URL。

描述

redirect 函数是一个顶级的服务器端 JavaScript 函数，并不与任何对象关联。

redirect 函数将客户浏览器重定向到由 location 参数指定的 URL。location 的值可以是相对路径或绝对路径。

当客户遇到 redirect 函数时，它将立即装载指定页，并忽略当前页。客户并不会执行或装载页面中 redirect 函数下方的任何 HTML 或脚本语句。

你可以使用 addClient 函数保留客户对象属性值。详情请看 addClient 。

示例

下面的例子使用了 redirect 函数重定向客户端浏览器：

redirect("http://www.royalairways.com/lw/apps/newhome.html")

而由 newhome.html 链接显示的页可能包含下列内容：

<H1>新位置</H1>
你试图访问的 URL 已经移动到了：<BR>
<LI><A HREF=http://www.royalairways.com/lw/apps/index.html>
http://www.royalairways.com/lw/apps/index.html</A>
<P>此信息将保留至 12/31/97 。

参看

addClient


JavaScript语言参考手册_全局函数

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

registerCFunction

 注册一个外部函数，以便在服务器端 JavaScript 应用程序中使用。

服务器端函数 |
实现版本 | LiveWire 1.0

语法

registerCFunction(JSFunctionName, libraryPath, externalFunctionName)

参数

JSFunctionName | 将要在 JavaScript 中调用的函数名称。
libraryPath | 库文件的完整文件名和路径名，使用操作系统规定的规范。
externalFunctionName | 函数定义在库中的名称。

描述

registerCFunction 是一个顶级的服务器端 JavaScript 函数，并不与任何对象关联。

使用 registerCFunction 可以使得一个外部函数对一个服务器端 JavaScript 应用程序可用。函数可以由任何语言写成，但是必须使用 C 调用规范。

要在服务器端 JavaScript 应用程序中使用外部函数，应该先用 registerCFunction 函数注册之，然后用 callC 函数调用之。只要应用程序注册了一个函数，就可以任意多次调用该函数。

registerCFunction 函数将在成功注册外部函数时返回 true，否则返回 false。例如，registerCFunction 将在 JavaScript 运行时刻引擎找不到库或找不到库中的函数时返回 false。

要在参数 libraryPath 中使用反斜线(\)字符作为目录分隔符的话，就必须输入双反斜线(\\)。单反斜线是用来定义转移字符的。

示例

参看 callC 函数的例子。

参看

callC


JavaScript语言参考手册_全局函数

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

ssjs_generateClientID

 返回一个唯一的字符串，你可用于唯一指定 client 对象。

服务器端函数 |
实现版本 | Netscape Server 3.0

语法

ssjs_generateClientID()

参数

无。

描述

此函数与 ssjs_getClientID 密切相关。请参看关于该函数的说明以获得关于这两个函数的信息及它们之间的区别。


JavaScript语言参考手册_全局函数

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

ssjs_getCGIVariable

 Returns the value of the specified environment variable set in the server process, including some CGI variables.

服务器端函数 |
实现版本 | Netscape Server 3.0

语法

ssjs_getCGIVariable(varName)

参数

varNameA string containing the name of the environment variable to retrieve.

描述

ssjs_getCGIVariable lets you access the environment variables set in the server process, including the CGI variables listed in 表 13.2.

表 13.2 CGI variables accessible through ssjs_getCGIVariable
Variable | 描述
AUTH_TYPE | The authorization type, if the request is protected by any type of authorization. Netscape web servers support HTTP basic access authorization. Example value: basic
HTTPS | If security is active on the server, the value of this variable is ON; otherwise, it is OFF. Example value: ON
HTTPS_KEYSIZE | The number of bits in the session key used to encrypt the session, if security is on. Example value: 128
HTTPS_SECRETKEYSIZE | The number of bits used to generate the server's private key. Example value: 128
PATH_INFO | Path information, as sent by the browser. Example value: /cgivars/cgivars.html
PATH_TRANSLATED | The actual system-specific pathname of the path contained in PATH_INFO. Example value: /usr/ns-home/myhttpd/js/samples/cgivars/cgivars.html
QUERY_STRING | Information from the requesting HTML page; if "?" is present, the information in the URL that comes after the "?". Example value: x=42
REMOTE_ADDR | The IP address of the host that submitted the request. Example value: 198.93.95.47
REMOTE_HOST | If DNS is turned on for the server, the name of the host that submitted the request; otherwise, its IP address. Example value: www.netscape.com
REMOTE_USER | The name of the local HTTP user of the web browser, if HTTP access authorization has been activated for this URL. Note that this is not a way to determine the user name of any person accessing your program. Example value: ksmith
REQUEST_METHOD | The HTTP 方法 associated with the request. An application can use this to determine the proper response to a request. Example value: GET
SCRIPT_NAME | The pathname to this page, as it appears in the URL. Example value: cgivars.html
SERVER_NAME | The hostname or IP address on which the JavaScript application is running, as it appears in the URL. Example value: piccolo.mcom.com
SERVER_PORT | The TCP port on which the server is running. Example value: 2020
SERVER_PROTOCOL | The HTTP protocol level supported by the client's software. Example value: HTTP/1.0
SERVER_URL | The URL that the user typed to access this server. Example value: https://piccolo:2020

If you supply an argument that isn't one of the CGI variables listed in n, the runtime engine looks for an environment variable by that name in the server environment. If found, the runtime engine returns the value; otherwise, it returns null. For example, the following code assigns the value of the standard CLASSPATH environment variable to the JavaScript variable classpath:

classpath = ssjs_getCGIVariable("CLASSPATH");


JavaScript语言参考手册_全局函数

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

ssjs_getClientID

 Returns the identifier for the client object used by some of JavaScript's client-maintenance techniques.

服务器端函数 |
实现版本 | Netscape Server 3.0

语法

ssjs_getClientID()

参数

 无。

描述

For some applications, you may want to store information specific to a client/application pair in the project or server objects. In these situations, you need a way to refer uniquely to the client/application pair. JavaScript provides two functions for this purpose, ssjs_generateClientID and ssjs_getClientID.

Each time you call ssjs_generateClientID, the runtime engine returns a new identifier. For this reason, if you use this function and want the identifier to last longer than a single client request, you need to store the identifier, possibly as a property of the client object.

If you use this function and store the ID in the client object, you may need to be careful that an intruder cannot get access to that ID and hence to sensitive information.

An alternative approach is to use the ssjs_getClientID function. If you use one of the server-side maintenance techniques for the client object, the JavaScript runtime engine generates and uses a identifier to access the information for a particular client/application pair.

When you use these maintenance techniques, ssjs_getClientID returns the identifier used by the runtime engine. Every time you call this function from a particular client/application pair, you get the same identifier. Therefore, you do not need to store the identifier returned by ssjs_getClientID. However, if you use any of the other maintenance techniques, this function returns "undefined"; if you use those techniques you must instead use the ssjs_generateClientID function.

If you need an identifier and you're using a server-side maintenance technique, you probably should use the ssjs_getClientID function. If you use this function, you do not need to store and track the identifier yourself; the runtime engine does it for you. However, if you use a client-side maintenance technique, you cannot use the ssjs_getClientID function; you must use the ssjs_generateClientID function.


JavaScript语言参考手册_全局函数

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

String

 将指定对象转换为字符串。

核心函数 |
实现版本 | Navigator 4.0, Netscape Server 3.0

语法

String(obj)

参数

obj 一个对象。

描述

如果对象是一个 Date 类型的对象，String 将返回一个该日期的字符串表示形式，其格式为：Thu Aug 18 04:37:43 Pacific Daylight Time 1983.

示例

下面的例子将把 Date 对象转变为可阅读的字符串。

<SCRIPT>
D = new Date (430054663215);
document.write (String(D) +" <BR>");
</SCRIPT> 屏幕将显示 "Thu Aug 18 04:37:43 Pacific Daylight Time 1983."

参看

String

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

回页面顶部 回页面顶部


JavaScript语言参考手册_全局函数

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

taint

向数据元素或脚本中添加污点。

核心函数 |
实现版本 | Navigator 3.0; 在 Navigator 4.0 中去除

语法

taint(dataElementName)

参数

dataElementName (可选)要污染的属性、变量、函数或对象。如果缺省的话，将会将污点添加到脚本自身。

描述

污点避免了其它脚本传递安全且私有的信息，如目录结构或用户进程历史。JavaScript 不能在没有最终用户许可的情况下向任何服务器传递污点值。

使用 taint 可以标记其它情况下不是污点的数据。

在某些情况下，控制流而不是数据流承载着污点信息。在这些情况下，污点奖添加到脚本的窗口中。你可以通过调用不带参数的 taint 向脚本窗口添加污点。

taint 并不修改其自身的参数，而是返回一个该值的副本，或者对于对象来说，返回一个对该值的未标记引用。

示例

下列语句将污点添加到属性，以便脚本不能在没有最终用户许可的情况下将其发送到另外的服务器：

taintedStatus=taint(window.defaultStatus)
// 在没有最终用户许可的情况下，taintedStatus 现在只能
//
  在 URL 中发送或者在表单中贴出。

参看

navigator.taintEnabled, untaint


JavaScript语言参考手册_全局函数

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

unescape

 返回指定值的 ASCII 字符串。

核心函数 |
实现版本 | Navigator 2.0

语法

unescape(string)

参数

string 包含形如“%xx”的字符的字符串，此处 xx 为两位十六进制数值。

描述

unescape 函数返回的字符串是一系列 ISO-Latin-1 字符集的字符。unescape 函数是一个顶级 JavaScript 函数，并不与任何对象关联。在服务器端的 JavaScript 中使用此函数解码 URL 中的名称/值。

示例

下面的客户端例子返回“&”：
unescape("%26")

下面的客户端例子返回“!#”：
unescape("%21%23")

在下面的服务器端例子中，val1 是以十六进制值传递给 request 对象的。该语句将 val1 的解码值赋给 myValue。
myValue = unescape(request.val1)

参看

escape


JavaScript语言参考手册_全局函数

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

untaint

从数据元素或脚本中移除污点。

核心函数 |
实现版本 | Navigator 3.0; 在 Navigator 4.0 中已移除

语法

untaint(dataElementName)

参数

dataElementName (可选) 要移除污点的属性、变量、函数或对象。如果缺省的话，将从脚本自身移除污点。

描述

污点将避免其它脚本传递安全和私有的信息，例如目录结构或用户的浏览历史。JavaScript 不能在没有最终用户许可的情况下向任何服务器传送带有污点的值。

使用 untaint 可以清除为了禁止其它脚本向不同的服务器发送的数据而标记的污点。

脚本只能去除其自身中含有的数据A script can untaint only data that originated in that script (that is, only data that has the script's taint code or has the identity (null) taint code). 如果你在使用 untaint 时带有其它服务器脚本的数据元素(或任何你不能去除污点的任何数据)，untaint 将返回没有更改的数据或者错误。

在某些情况下，控制流包含了污点信息而不是数据流。在这些情况下，污点将被添加到脚本窗口中。你可以调用不带参数的 untaint 去除脚本窗口的污点，但窗口必须只包含当前窗口的污点。

untaint 并不修改其参数，而返回值的未标记副本，或者对象值的未标记引用。

示例

下面的语句将去除属性的污点，这样脚本就可以将其向其它服务器中发送了：

untaintedStatus=untaint(window.defaultStatus)
// untaintedStatus 现在可以在 URL 或由其它脚本提交的表单中发送了

参看

navigator.taintEnabled, taint


JavaScript语言参考手册_全局函数

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

write

 根据表达式生成 HTML，并将其送到客户端。

服务器端函数 |
实现版本 | LiveWire 1.0

语法

write(expression)

参数

expression 一个合法的 JavaScript 表达式。

描述

write 函数将导致服务器端 JavaScript 生成要发送到 客户端的 HTML。客户端将把生成的 HTML 认为是静态的 HTML。服务器端的 write 函数与客户端的 document.write 方法类似。

为了提升效率，服务器上的 JavaScript 引擎将把要发送到客户的数据缓冲起来，等到了 64 千字节的时候统一发送。你可以使用 flush 函数控制何时向客户端发送数据。

write 函数是一个顶级的服务器端 JavaScript 函数，并不与任何对象关联。不要混淆 File 对象的 write 方法和 write 函数。write 函数将数据输出到客户端；而 write 方法将数据输出到服务器的物理文件中。

示例

在下面的例子中，write 函数传送了一个字符串、一个变量和一个 BR 标签：

write("此操作返回 " + returnValue + "<BR>")

如果 returnValue 是 57 的话，该例子将显示如下内容：

此操作返回 57

参看

flush

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


JavaScript语言参考手册_简介

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

第一章
简介

本章简要介绍了 JavaScript，Netscape 跨平台基于对象的用于客户/服务器应用的脚本语言。

JavaScript 可以让你创建直接运行于 Internet 上的应用。使用 JavaScript，你可以创建你所需要的动态 HTML 页面，用于处理用户输入及使用特殊的对象、文件和关系数据库维护稳固的数据。从内部的协作信息管理和内联网发布到大型超市的电子交易和商务，都可应用此便利。通过 JavaScript 的 LiveConnect 功能，你的程序可以访问 Java 和 CORBA 发布的应用程序。

服务器端和客户端 JavaScript 共享相同的核心语言。该核心语言完全符合 ECMA-262，这是欧洲标准体制订的脚本语言标准，除此之外还有一些额外的加强。核心语言包含一组核心对象，如 Array 和 Date 对象。它还定义了其他语言特性，如表达式、语句和操作符。尽管服务器端和客户端 JavaScript 使用相同的核心功能，在某些情况下它们使用这些核心功能还是有相当大的不同的。你可以下载一份 PDF 版本 的 ECMA-262 标准。

JavaScript 的组成在图 1.1举例说明。

图 1.1 JavaScript 语言。

客户端 JavaScript (或 Navigator JavaScript) 在核心语言外面还封装了额外的特性，如只与在浏览器中运行 JavaScript 有关的预定义对象。服务器端 JavaScript 则封装了只与在服务器上运行 JavaScript 有关的预定义对象和函数。

客户端 JavaScript 直接嵌入 HTML 页面中，在运行时完全由浏览器解释。而由于服务器一般都会针对自身的任务做一定的特殊优化，在服务器端运行特定的 JavaScript 代码将会极大程度上改善页面的处理速度。下面的两节会向你介绍 JavaScript 是如何在客户端和服务器端工作的。

客户端 JavaScript

像 Netscape Navigator 2.0(或更新版本) 这样的 Web 浏览器可以解释嵌入 HTML 页面的 JavaScript 语句。当浏览器(或客户)需求这样的页的时候，服务器将会将整个文档的内容(包括 HTML 和 JavaScript 语句)通过网络发送到客户那里。客户从头到尾阅读页面，显示 HTML 结果并同时执行 JavaScript 语句。这个过程将产生用户看到的结果，图示请看图 1.2。

图 1.2 客户端 JavaScript。

嵌入 HTML 页面的客户端 JavaScript 语句可以相应用户的事件，如鼠标单击，表单输入和页面导航。例如，你可以编写一个 JavaScript 函数用于校验用户在一个需要填入电话号码或邮政编码的表单中输入的信息。不需要任何的网络传输，嵌入 HTML 页面的 JavaScript 就可以检查输入的数据并向输入了无效数据的用户显示一个提示对话框。

服务器端 JavaScript

在服务器上，JavaScript 也是嵌入 HTML 页面的。服务器端的语句可以连接到不同供应上的关系数据库中，共享同一应用的用户之间的信息，访问服务器上的文件系统，或者通过 LiveConnect 和 Java 与其它应用通讯。一个已经编译好的 JavaScript 应用除了服务器端 JavaScript 之外还可包含客户端 JavaScript。

与纯粹的服务器端 JavaScript 脚本相比，使用服务器端 JavaScript 的应用是编译为字节代码可执行文件的。这些应用程序可执行文件运行于装有 JavaScript 运行时刻引擎的 Web 服务器中。由此原因，创建 JavaScript 应用程序分为两个步骤。

第一个步骤，如图 1.3，你(开发员)需要创建 HTML 页面(可以同时包含客户端和服务器端 JavaScript 语句) 和 JavaScript 文件。你可以将所有这些文件编译为一个单一的可执行文件。

图 1.3 开发过程中的服务器端 JavaScript。

在第二个步骤中，如图 1.4，客户浏览器将会导致对应用中某一章的需求。运行时刻引擎将使用应用程序的可执行文件查阅源页面并动态生成要返回的 HTML 代码。它将运行在页面上发现的任何服务器端 JavaScript 语句。这些语句的结果可能会向 HTML 页面中添加新的 HTML 代码或客户端 JavaScript 语句。然后该运行时刻引擎将把结果页面通过网络发送到 Navigator 的客户端，并显示之。

图 1.4 运行时刻的服务器端 JavaScript。

对比标准的通用网关接口(CGI)程序，所有的 JavaScript 都是直接集成到 HTML 页面中的，这将使得开发和维护变得更加容易。JavaScript 的进程管理服务包含了你可用于维护客户需求、多客户和多个应用之间的交叉数据的对象。而JavaScript 的 LiveWire 数据库服务提供了用于数据库访问的对象，你可用之访问任何支持 SQL 的数据库服务器。

JavaScript 对象

JavaScript 预先定义了核心语言的对象，以及对于客户端和服务器端 JavaScript 额外的附加内容。

JavaScript 有下列核心对象：

Array, Boolean, Date, Function, Math, Number, Object, String

附加的客户端对象有：

Anchor, Applet, Area, Button, Checkbox, document, event, FileUpload, Form, Frame, Hidden, History, Image, Layer, Link, Location, MimeType, navigator, Option, Password, Plugin, Radio, Reset, screen, Select, Submit, Text, Textarea, Window

这些对象描述了与在 Web 浏览器中运行 JavaScript 相关的信息。其中许多对象之间通过属性值的形式互相交织在一起。例如，为了访问文档中的图像，你需要使用 document.images 数组，而该数组的每一个元素都是一个 Image 对象。图 1.5 显示了客户端对象的包含层次。

图 1.5 客户端对象件的包含关系

服务器端对象有：

blob, client, Connection, Cursor, database, DbPool, File, Lock, project, request, Resultset, SendMail, server, Stproc

某些服务器端对象也有一定的包含层次，如图 1.6。

图 1.6 LiveWire 对象中的包含关系

JavaScript 安全性

Navigator 2.02 及以后版本会自动避免服务器上的脚本访问不同服务器上文档的属性。此限制也避免了脚本获取像目录结构或用户进程历史这样的私有信息。

而 Navigator 3.0 中的 JavaScript 有一个叫做数据污点的特性，其中保留了安全限制，但是提供了对于页面中指定部件的安全访问手段。

  • 当允许数据污点的时候，一个窗口中的 JavaScript 可以观看另一个窗口的属性，而不管另外的窗口是从哪个服务器上装入的。不过，另外窗口的作者可以将某些属性值或必须是安全或私有的数据标为带有污点，因为 JavaScript 不能在没有用户许可的情况下向任何服务器发送这些带有污点的数据。

  • 当禁止数据污点的时候，脚本不能访问其它服务器窗口的任何属性。
在 Navigator 4.0 中已经删除了数据污点这一特性。取而代之的，Navigator 4.0 提供了签字的 JavaScript 脚本用于更加可靠和灵活的安全性。

要获得关于数据污点和签字脚本更多的信息，请看“JavaScript 指南”中的第七章，“JavaScript 安全性”。

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


JavaScript语言参考手册_LiveWire 数据库服务

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

第十章
LiveWire 数据库服务

本章包含了与 LiveWire 相关的服务器端对象：database、DbPool、Connection、Cursor、Stproc、Resultset 和 blob。

表 10.1 本章用到的对象总览。

表 10.1 LiveWire 对象
对象 | 描述
blob | 提供了显示和链接到 BLOb 数据的功能。
Connection | 描述了一池连接中的一个单个的数据库连接。
Cursor | 描述了一个数据库临时表。
database | 描述了一个数据库连接。
DbPool | 描述了一个数据库连接池。
Resultset | 描述了数据库存储过程返回的信息。
Stproc | 描述了一个数据库存储的过程。

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


JavaScript语言参考手册_LiveWire 数据库服务

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

database

 Lets an application interact with a relational database.

服务器端对象 |
实现版本 | LiveWire 1.0 Netscape Server 3.0: 添加了 storedProc and storedProcArgs 方法s.

创建源

The JavaScript runtime engine on the server automatically creates the database object. You indicate that you want to use this object by calling its connect method.

描述

The JavaScript runtime engine on the server creates a database object when an application connects to a database server. Each application has only one database object. You can use the database object to interact with the database on the server. Alternatively, you can use the DbPool and Connection objects.

You can use the database object to connect to the database server and perform the following tasks:

  • Display the results of a query as an HTML 表
    •
  • Execute SQL statements on the database server
    •
  • Manage transactions
    •
  • Run stored procedures
    •
  • Handle errors returned by the target database
The scope of a database connection created with the database object is a single HTML page. That is, as soon as control leaves the HTML page, the runtime engine closes the database connection. You should close all open cursors, stored-procedure objects, and result sets before the end of the page.

If possible, your application should make the database connection on its initial page. Doing so prevents conflicts from multiple client requests trying to manipulate the status of the connections at once.

Internally, JavaScript creates the database object as an instance of the DbBuiltin class. In most circumstances, this is an implementation detail you do not need to be aware of, because you cannot create instances of this class. However, you can use the prototype property of the DbBuiltin class to add a property to the predefined database object. If you do so, that addition applies to the database object when used in all applications on your server, not just in the single application that made the change. This allows you to expand the capabilities of this object for your entire server.

属性概览

prototypeAllows the addition of properties to the database object.

方法概览

beginTransaction | Begins an SQL transaction.
commitTransaction | Commits the current SQL transaction.
connect | Connects to a particular configuration of database and user.
connected | Returns true if the database pool (and hence this connection) is connected to a database.
cursor | Creates a database cursor for the specified SQL SELECT statement.
disconnect | Disconnects all connections from the database.
execute | Performs the specified SQL statement.
majorErrorCode | Major error code returned by the database server or ODBC.
majorErrorMessage | Major error message returned by the database server or ODBC.
minorErrorCode | Secondary error code returned by vendor library.
minorErrorMessage | Secondary message returned by vendor library.
rollbackTransaction | Rolls back the current SQL transaction.
SQL表 | Displays query results. Creates an HTML 表 for results of an SQL SELECT statement.
storedProc | Creates a stored-procedure object and runs the specified stored procedure.
storedProcArgs | Creates a prototype for a Sybase stored procedure.
toString | Returns a string representing the specified object.

示例

The following example creates a database object and opens a standard connection to the customer database on an Informix server. The name of the server is blue, the user name is ADMIN, and the password is MANAGER.

database.connect("INFORMIX", "blue", "ADMIN", "MANAGER", "inventory") In this example, many clients can connect to the database simultaneously, but they all share the same connection, user name, and password.

参看

Cursor, database.connect

Transactions

A transaction is a group of database actions that are performed together. Either all the actions succeed together or all fail together. When you attempt to have all of the actions make permanent changes to the database, you are said to commit a transaction. You can also roll back a transaction that you have not committed; this cancels all the actions.

You can use explicit transaction control for any set of actions, by using the beginTransaction, commitTransaction, and rollbackTransaction methods. If you do not control transactions explicitly, the runtime engine uses the underlying database's autocommit feature to treat each database modification as a separate transaction. Each statement is either committed or rolled back immediately, based on the success or failure of the individual statement. Explicitly managing transactions overrides this default behavior.

In some databases, such as Oracle, autocommit is an explicit feature that LiveWire turns on for individual statements. In others, such as Informix, it is the default behavior when you do not create a transaction.

NOTE: You must use explicit transaction control any time you make changes to a database. If you do not, your database may return errors; even it does not, you cannot be guaranteed of data integrity without using transactions. In addition, any time you use cursors, you are encourage to use explicit transactions to control the consistency of your data.
For the database object, the scope of a transaction is limited to the current request (HTML page) in an application. If the application exits the page before calling the commitTransaction or rollbackTransaction method, then the transaction is automatically either committed or rolled back, depending on the setting for the commitflag parameter when the connection was established. This parameter is provided either to the pool object's constructor or to its connect method. For further information, see connect.

属性

prototype

 Represents the prototype for this class. You can use the prototype of the DbBuiltin class to add properties or methods to the database object. For information on prototypes, see Function.prototype.

属性源 | database
实现版本 | LiveWire 1.0

方法

beginTransaction

 Begins a new SQL transaction.

方法源 | database
实现版本 | LiveWire 1.0

语法

beginTransaction()

参数

 无。

返回

0 if the call was successful; otherwise, a nonzero status code based on any error message passed by the database. If the method returns a nonzero status code, use the associated majorErrorCode and majorErrorMessage methods to interpret the cause of the error.

描述

All subsequent actions that modify the database are grouped with this transaction, known as the current transaction.

For the database object, the scope of a transaction is limited to the current request (HTML page) in the application. If the application exits the page before calling the commitTransaction or rollbackTransaction method, then the transaction is automatically either committed or rolled back, based on the setting of the commitflag parameter when the connection was established. This parameter is provided when you make the connection by calling database.connect.

For Connection objects, the scope of a transaction is limited to the lifetime of that object. If the connection is released or the pool of connections is closed before calling the commitTransaction or rollbackTransaction method, then the transaction is automatically either committed or rolled back, based on the setting of the commitflag parameter when the connection was established. This parameter is provided when you make the connection by calling the connect method or in the DbPool constructor.

If there is no current transaction (that is, if the application has not called beginTransaction), calls to commitTransaction and rollbackTransaction are ignored.

The LiveWire Database Service does not support nested transactions. If you call beginTransaction when a transaction is already open (that is, you've called beginTransaction and have yet to commit or roll back that transaction), you'll get an error message.

示例

This example updates the rentals 表 within a transaction. The values of customerID and videoID are passed into the cursor method as properties of the request object. When the videoReturn Cursor object opens, the next method navigates to the only record in the virtual 表 and updates the value in the returnDate field.

The variable x is assigned a database status code to indicate if the updateRow method is successful. If updateRow succeeds, the value of x is 0, and the transaction is committed; otherwise, the transaction is rolled back.

// Begin a transaction
database.beginTransaction();
// Create a Date object with the value of today's date
today = new Date();
// Create a cursor with the rented video in the virtual 表
videoReturn = database.cursor("SELECT * FROM rentals WHERE
customerId = " + request.customerID + " AND
videoId = " + request.videoID, true);
// Position the pointer on the first row of the cursor
// and update the row
videoReturn.next()
videoReturn.returndate = today;
x = videoReturn.updateRow("rentals");
// End the transaction by committing or rolling back
if (x == 0) {
database.commitTransaction() }
else {
database.rollbackTransaction() }
// Close the cursor
videoReturn.close();

commitTransaction

Commits the current transaction.

方法源 | database
实现版本 | LiveWire 1.0

语法

commitTransaction()

参数

 无。

返回

0 if the call was successful; otherwise, a nonzero status code based on any error message passed by the database. If the method returns a nonzero status code, use the associated majorErrorCode and majorErrorMessage methods to interpret the cause of the error.

描述

This method attempts to commit all actions since the last call to beginTransaction.

For the database object, the scope of a transaction is limited to the current request (HTML page) in the application. If the application exits the page before calling the commitTransaction or rollbackTransaction method, then the transaction is automatically either committed or rolled back, based on the setting of the commitflag parameter when the connection was established. This parameter is provided when you make the connection with the database or DbPool object.

For Connection objects, the scope of a transaction is limited to the lifetime of that object. If the connection is released or the pool of connections is closed before calling the commitTransaction or rollbackTransaction method, then the transaction is automatically either committed or rolled back, based on the commitFlag value.

If there is no current transaction (that is, if the application has not called beginTransaction), calls to commitTransaction and rollbackTransaction are ignored.

The LiveWire Database Service does not support nested transactions. If you call beginTransaction when a transaction is already open (that is, you've called beginTransaction and have yet to commit or roll back that transaction), you'll get an error message.

connect

Connects the pool to a particular configuration of database and user.

方法源 | database
实现版本 | LiveWire 1.0

语法

connect (dbtype, serverName, username, password, databaseName) connect (dbtype, serverName, username, password, databaseName, maxConnections) connect (dbtype, serverName, username, password, databaseName, maxConnections, commitflag)

参数

dbtypeDatabase type; one of ORACLE, SYBASE, INFORMIX, DB2, or ODBC.
serverNameName of the database server to which to connect. The server name typically is established when the database is installed and is different for different database types:DB2: Local database alias. On both NT and UNIX, this is set up by the client or the DB2 Command Line Processor.Informix: Informix server. On NT, this is specified with the setnet32 utility; on UNIX, in the sqlhosts file.Oracle: Service. On both NT and UNIX, this specified in the tnsnames.ora file. On NT, you can use the SQL*Net easy configuration to specify it. If your Oracle database server is local, specify the empty string for this argument.ODBC: Data source name. On NT, this is specified in the ODBC Administrator; on UNIX, in the .odbc.ini file. If you are using the Web Server as a user the file .odbc.ini must be in your home directory; if as a system, it must be in the root directory.Sybase: Server name (the DSQUERY parameter). On NT, this is specified with the sqledit utility; on UNIX, with the sybinit utility.If in doubt, see your database or system administrator. For ODBC, this is the name of the ODBC service as specified in Control Panel.
userNameName of the user to connect to the database. Some relational database management systems (RDBMS) require that this be the same as your operating system login name; others maintain their own collections of valid user names. See your system administrator if you are in doubt.
passwordUser's password. If the database does not require a password, use an empty string ("").
databaseNameName of the database to connect to for the given serverName. If your database server supports the notion of multiple databases on a single server, supply the name of the database to use. If it does not, use an empty string (""). For Oracle, ODBC, and DB2, you must always use an empty string.For Oracle, specify this information in the tnsnames.ora file.For ODBC, if you want to connect to a particular database, specify the database name specified in the datasource definition.For DB2, there is no concept of a database name; the database name is always the server name (as specified with serverName).
maxConnections(Optional) Number of connections to be created and cached in the pool. The runtime engine attempts to create as many connections as specified with this parameter. If successful, it stores those connections for later use.If you do not supply this parameter, its value is whatever you specify in the Application Manager when you install the application as the value for Built-in Maximum Database Connections.Remember that your database client license probably specifies a maximum number of connections. Do not set this parameter to a number higher than your license allows. For Sybase, you can have at most 100 connections.If your database client library is not multithreaded, it can only support one connection at a time. In this case, your application performs as though you specified 1 for this parameter. For a current list of which database client libraries are multithreaded, see the Enterprise Server 3.0 Release Notes
commitFlag(Optional) A Boolean value indicating whether to commit a pending transaction when the connection is released or the object is finalized.(If the transaction is on a single page, the object is finalized at the end of the page. If the transaction spans multiple pages, the object is finalized when the connection returns to the pool.)If this parameter is false, a pending transaction is rolled back. If this parameter is true, a pending transaction if committed. For DbPool, the default value is false; for database, the default value is true. If you specify this parameter, you must also specify the maxConnections parameter.

返回

0 if the call was successful; otherwise, a nonzero status code based on any error message passed by the database. If the method returns a nonzero status code, use the associated majorErrorCode and majorErrorMessage methods to interpret the cause of the error.

描述

When you call this method, the runtime engine first closes and releases any currently open connections. It then reconnects the pool with the new configuration. You should be sure that all connections have been released before calling this method.

The first version of this method creates and caches one connection. When this connection goes out of scope, pending transactions are rolled back.

The second version of this method attempts to create as many connections as specified by the maxConnections parameter. If successful, it stores those connections for later use. If the runtime engine does not obtain the requested connections, it returns an error. When this connection goes out of scope, pending transactions are rolled back.

The third version of this method does everything the second version does. In addition, the commitflag parameter indicates what to do with pending transactions when this connection goes out of scope. If this parameter is false (the default), a pending transaction is rolled back. If this parameter is true, a pending transaction if committed.

If possible, your application should call this method on its initial page. Doing so prevents conflicts from multiple client requests trying to connect and disconnect.

示例

The following statement creates four connections to an Informix database named mydb on a server named myserver, with user name SYSTEM and password MANAGER. Pending transactions are rolled back at the end of a client request:

connected

Tests whether the database pool and all of its connections are connected to a database.

方法源 | database
实现版本 | LiveWire 1.0

语法

connected()

参数

 无。

返回

True if the pool (and hence a particular connection in the pool) is currently connected to a database; otherwise, false.

描述

The connected method indicates whether this object is currently connected to a database.

If this method returns false for a Connection object, you cannot use any other methods of that object. You must reconnect to the database, using the DbPool object, and then get a new Connection object. Similarly, if this method returns false for the database object, you must reconnect before using other methods of that object.

示例

示例 1: The following code fragment checks to see if the connection is currently open. If it's not, it reconnects the pool and reassigns a new value to the myconn variable.

if (!myconn.connected()) {
mypool.connect ("INFORMIX", "myserver", "SYSTEM", "MANAGER", "mydb", 4);
myconn = mypool.connection;
}
示例 2: The following example uses an if condition to determine if an application is connected to a database server. If the application is connected, the isConnectedRoutine function runs; if the application is not connected, the isNotConnected routine runs.

if(database.connected()) {
isConnectedRoutine() }
else {
isNotConnectedRoutine() }

cursor

Creates a Cursor object.

方法源 | database
实现版本 | LiveWire 1.0

语法

cursor("sqlStatement",upda表)

参数

sqlStatement | A JavaScript string representing a SQL SELECT statement supported by the database server.
upda表 | (Optional) A Boolean parameter indicating whether or not the cursor is upda表.

返回

A new Cursor object.

描述

The cursor method creates a Cursor object that contains the rows returned by a SQL SELECT statement. The SELECT statement is passed to the cursor method as the sqlStatement argument. If the SELECT statement does not return any rows, the resulting Cursor object has no rows. The first time you use the next method on the object, it returns false.

You can perform the following tasks with the Cursor object:

  • Modify data in a server 表.
    •
  • Navigate in a server 表.
    •
  • Customize the display of the virtual 表 returned by a database query.
    •
  • Run stored procedures.
The cursor method does not automatically display the returned data. To display this data, you must create custom HTML code. This HTML code may display the rows in an HTML 表, as shown in Example 3. The SQL表 method is an easier way to display the output of a database query, but you cannot navigate, modify data, or control the format of the output.

The optional parameter upda表 specifies whether you can modify the Cursor object you create with the cursor method. To create a Cursor object you can modify, specify upda表 as true. If you do not specify a value for the upda表 parameter, it is false by default.

If you create an upda表 Cursor object, the virtual 表 returned by the sqlStatement parameter must be upda表. For example, the SELECT statement in the sqlStatement parameter cannot contain a GROUP BY clause; in addition, the query usually must retrieve key values from a 表. For more information on constructing upda表 queries, consult your database vendor's documentation.

示例

示例 1. The following example creates the upda表 cursor custs and returns the columns ID, CUST_NAME, and CITY from the customer 表:

custs = database.cursor("select id, cust_name, city from customer", true) 示例 2. You can construct the SELECT statement with the string concatenation operator (+) and string variables such as client or request property values, as shown in the following example:

custs = database.cursor("select * from customer
where customerID = " + request.customerID); 示例 3. The following example demonstrates how to format the virtual 表 returned by the cursor method as an HTML 表. This example first creates Cursor object named videoSet and then displays two columns of its data (videoSet.title and videoSet.synopsis).

// Create the videoSet cursor
<SERVER>
videoSet = database.cursor("select * from videos
where videos.numonhand > 0 order by title");
</SERVER> // Begin creating an HTML 表 to contain the virtual 表
// Specify titles for the two columns in the virtual 表
<表 BORDER>
<CAPTION> Videos on Hand </CAPTION>
<TR>
<TH>Title</TH>
<TH>Synopsis</TH>
</TR> // Use a while loop to iterate over each row in the cursor
<SERVER>
while(videoSet.next()) {
</SERVER> // Use write statements to display the data in both columns
<TR>
<TH><A HREF=\Q"rent.html?videoID="+videoSet.id\Q>
<SERVER>write(videoSet.title)</SERVER></A></TH>
<TD><SERVER>write(videoSet.synopsis)</SERVER></TD>
</TR> // End the while loop
<SERVER>
}
</SERVER> // End the HTML 表
</表> The values in the videoSet.title column are displayed within the A tag so a user can click them as links. When a user clicks a title, the rent.html page opens and the column value videoSet.id is passed to it as the value of request.videoID.

参看

database.SQL表, database.cursor

disconnect

Disconnects all connections in the pool from the database.

方法源 | database
实现版本 | LiveWire 1.0

语法

disconnect()

参数

 无。

返回

0 if the call was successful; otherwise, a nonzero status code based on any error message passed by the database. If the method returns a nonzero status code, use the associated majorErrorCode and majorErrorMessage methods to interpret the cause of the error.

描述

Before calling the disconnect method, you must first call the release method for all connections in this database pool. Otherwise, the connection is still considered in use by the system, so the disconnect waits until all connections are released.

After disconnecting from a database, the only methods of this object you can use are connect and connected.

示例

The following example uses an if condition to determine if an application is connected to a database server. If the application is connected, the application calls the disconnect method; if the application is not connected, the isNotConnected routine runs.

if(database.connected()) {
database.disconnect() }
else {
isNotConnectedRoutine() }

execute

Performs the specified SQL statement. Use for SQL statements other than queries.

方法源 | database
实现版本 | LiveWire 1.0

语法

execute (stmt)

参数

stmtA string representing the SQL statement to execute.

返回

0 if the call was successful; otherwise, a nonzero status code based on any error message passed by the database. If the method returns a nonzero status code, use the associated majorErrorCode and majorErrorMessage methods to interpret the cause of the error.

描述

This method enables an application to execute any data definition language (DDL) or data manipulation language (DML) SQL statement supported by the database server that does not return a cursor, such as CREATE, ALTER, or DROP.

Each database supports a standard core of DDL and DML statements. In addition, they may each also support DDL and DML statements specific to that database vendor. You can use execute to call any of those statements. However, each database vendor may also provide functions you can use with the database that are not DDL or DML statements. You cannot use execute to call those functions. For example, you cannot call the Oracle describe function or the Informix load function from the execute method.

Although technically you can use execute to perform data modification (INSERT, UPDATE, and DELETE statements), you should instead use Cursor objects. This makes your application more database-independent. Cursors also provide support for binary large object (BLOb) data.

When using the execute method, your SQL statement must strictly conform to the语法 requirements of the database server. For example, some servers require each SQL statement to be terminated by a semicolon. See your server documentation for more information.

If you have not explicitly started a transaction, the single statement is automatically committed.

示例

In the following example, the execute method is used to delete a customer from the customer 表. customer.ID represents the unique ID of a customer that is in the ID column of the customer 表. The value for customer.ID is passed into the DELETE statement as the value of the ID property of request.

if(request.ID != null) {
database.execute("delete from customer
where customer.ID = " + request.ID)
}

majorErrorCode

Major error code returned by the database server or ODBC.

方法源 | database
实现版本 | LiveWire 1.0

语法

majorErrorCode()

参数

 无。

返回

The result returned by this method depends on the database server being used:

  • Informix: the Informix error code.

  • Oracle: the code as reported by Oracle Call-level Interface (OCI).

  • Sybase: the DB-Library error number or the SQL server message number.

描述

 SQL statements can fail for a variety of reasons, including referential integrity constraints, lack of user privileges, record or 表 locking in a multiuser database, and so on. When an action fails, the database server returns an error message indicating the reason for failure. The LiveWire Database Service provides two ways of getting error information: from the status code returned by various methods or from special properties containing error messages and codes.

Status codes are integers between 0 and 27, with 0 indicating a successful execution of the statement and other numbers indicating an error, as shown in 表 10.2.:

表 10.2 Database status codes.
Status Code | Explanation | Status Code | Explanation
0 | No error | 14 | Null reference parameter
1 | Out of memory | 15 | Connection object not found
2 | Object never initialized | 16 | Required information is missing
3 | Type conversion error | 17 | Object cannot support multiple readers
4 | Database not registered | 18 | Object cannot support deletions
5 | Error reported by server | 19 | Object cannot support insertions
6 | Message from server | 20 | Object cannot support updates
7 | Error from vendor's library | 21 | Object cannot support updates
8 | Lost connection | 22 | Object cannot support indices
9 | End of fetch | 23 | Object cannot be dropped
10 | Invalid use of object | 24 | Incorrect connection supplied
11 | Column does not exist | 25 | Object cannot support privileges
12 | Invalid positioning within object (bounds error) | 26 | Object cannot support cursors
13 | Unsupported feature | 27 | Unable to open

示例

This example updates the rentals 表 within a transaction. The updateRow method assigns a database status code to the statusCode variable to indicate whether the method is successful.

If updateRow succeeds, the value of statusCode is 0, and the transaction is committed. If updateRow returns a statusCode value of either five or seven, the values of majorErrorCode, majorErrorMessage, minorErrorCode, and minorErrorMessage are displayed. If statusCode is set to any other value, the errorRoutine function is called.

database.beginTransaction()
statusCode = cursor.updateRow("rentals")
if (statusCode == 0) {
database.commitTransaction()
}
if (statusCode == 5 || statusCode == 7) {
write("The operation failed to complete.<BR>"
write("Contact your system administrator with the following:<P>"
write("The value of statusCode is " + statusCode + "<BR>")
write("The value of majorErrorCode is " +
database.majorErrorCode() + "<BR>")
write("The value of majorErrorMessage is " +
database.majorErrorMessage() + "<BR>")
write("The value of minorErrorCode is " +
database.minorErrorCode() + "<BR>")
write("The value of minorErrorMessage is " +
database.minorErrorMessage() + "<BR>")
database.rollbackTransaction()
}
else {
errorRoutine()
}

majorErrorMessage

Major error message returned by database server or ODBC. For server errors, this typically corresponds to the server's SQLCODE.

方法源 | database
实现版本 | LiveWire 1.0

语法

majorErrorMessage()

参数

 无。

返回

A string describing that depends on the database server:

  • Informix: "Vendor Library Error: string," where string is the error text from Informix.

  • Oracle: "Server Error: string," where string is the translation of the return code supplied by Oracle.

  • Sybase: "Vendor Library Error: string," where string is the error text from DB-Library or "Server Error string," where string is text from the SQL server, unless the severity and message number are both 0, in which case it returns just the message text.

描述

 SQL statements can fail for a variety of reasons, including referential integrity constraints, lack of user privileges, record or 表 locking in a multiuser database, and so on. When an action fails, the database server returns an error message indicating the reason for failure. The LiveWire Database Service provides two ways of getting error information: from the status code returned by connection and DbPool methods or from special connection or DbPool properties containing error messages and codes.

示例

See database.majorErrorCode.

minorErrorCode

Secondary error code returned by database vendor library.

方法源 | database
实现版本 | LiveWire 1.0

语法

minorErrorCode()

参数

 无。

返回

The result returned by this method depends on the database server:

  • Informix: the ISAM error code, or 0 if there is no ISAM error.

  • Oracle: the operating system error code as reported by OCI.

  • Sybase: the severity level, as reported by DB-Library or the severity level, as reported by the SQL server.

minorErrorMessage

 Secondary message returned by database vendor library.

方法源 | database
实现版本 | LiveWire 1.0

语法

minorErrorMessage()

参数

 无。

返回

The string returned by this method depends on the database server:

  • Informix: "ISAM Error: string," where string is the text of the ISAM error code from Informix, or an empty string if there is no ISAM error.

  • Oracle: the Oracle server name.

  • Sybase: the operating system error text, as reported by DB-Library or the SQL server name.

rollbackTransaction

 Rolls back the current transaction.

方法源 | database
实现版本 | LiveWire 1.0

语法

rollbackTransaction()

参数

 无。

返回

0 if the call was successful; otherwise, a nonzero status code based on any error message passed by the database. If the method returns a nonzero status code, use the associated majorErrorCode and majorErrorMessage methods to interpret the cause of the error.

描述

This method will undo all modifications since the last call to beginTransaction.

For the database object, the scope of a transaction is limited to the current request (HTML page) in the application. If the application exits the page before calling the commitTransaction or rollbackTransaction method, then the transaction is automatically either committed or rolled back, based on the setting of the commitflag parameter when the connection was established. This parameter is provided when you make the connection with the database or DbPool object.

For Connection objects, the scope of a transaction is limited to the lifetime of that object. If the connection is released or the pool of connections is closed before calling the commitTransaction or rollbackTransaction method, then the transaction is automatically either committed or rolled back, based on the commitFlag value.

If there is no current transaction (that is, if the application has not called beginTransaction), calls to commitTransaction and rollbackTransaction are ignored.

The LiveWire Database Service does not support nested transactions. If you call beginTransaction when a transaction is already open (that is, you've called beginTransaction and have yet to commit or roll back that transaction), you'll get an error message.

SQL表

Displays query results. Creates an HTML 表 for results of an SQL SELECT statement.

方法源 | database
实现版本 | LiveWire 1.0

语法

SQL表 (stmt)

参数

stmtA string representing an SQL SELECT statement.

返回

A string representing an HTML 表, with each row and column in the query as a row and column of the 表.

描述

Although SQL表 does not give explicit control over how the output is formatted, it is the easiest way to display query results. If you want to customize the appearance of the output, use a Cursor object to create your own display function.

Note

Every Sybase 表 you use with a cursor must have a unique index.

示例

If connobj is a Connection object and request.sql contains an SQL query, then the following JavaScript statements display the result of the query in a 表:

write(request.sql)
connobj.SQL表(request.sql) The first line simply displays the SELECT statement, and the second line displays the results of the query. This is the first part of the HTML generated by these statements:

select * from videos
<表 BORDER>
<TR>
<TH>title</TH>
<TH>id</TH>
<TH>year</TH>
<TH>category</TH>
<TH>quantity</TH>
<TH>numonhand</TH>
<TH>synopsis</TH>
</TR>
<TR>
<TD>A Clockwork Orange</TD>
<TD>1</TD>
<TD>1975</TD>
<TD>Science Fiction</TD>
<TD>5</TD>
<TD>3</TD>
<TD> Little Alex, played by Malcolm Macdowell,
and his droogies stop by the Miloko bar for a
refreshing libation before a wild night on the town.
</TD>
</TR>
<TR>
<TD>Sleepless In Seattle</TD>
... As this example illustrates, SQL表 generates an HTML 表, with column headings for each column in the database 表 and a row in the 表 for each row in the database 表.

storedProc

Creates a stored-procedure object and runs the specified stored procedure.

方法源 | database
实现版本 | Netscape Server 3.0

语法

storedProc (procName, inarg1, inarg2, ..., inargN)

参数

procName | A string specifying the name of the stored procedure to run.
inarg1, ..., inargN | The input parameters to be passed to the procedure, separated by commas.

返回

A new Stproc object.

描述

The scope of the stored-procedure object is a single page of the application. In other words, all methods to be executed for any instance of storedProc must be invoked on the same application page as the page on which the object is created.

When you create a stored procedure, you can specify default values for any of the parameters. Then, if a parameter is not included when the stored procedure is executed, the procedure uses the default value. However, when you call a stored procedure from a server-side JavaScript application, you must indicate that you want to use the default value by typing "/Default/" in place of the parameter. (Remember that JavaScript is case sensitive.) For example: spObj = connobj.storedProc ("newhire", "/Default/", 3)

storedProcArgs

Creates a prototype for a DB2, ODBC, or Sybase stored procedure.

方法源 | database
实现版本 | Netscape Server 3.0

语法

storedProcArgs (procName, type1, ..., typeN)

参数

procName | The name of the procedure.
type1, ..., typeN | Each typeI is one of: "IN", "OUT", or "INOUT" Specifies the type of each parameter: input ("IN"), output ("OUT"), or both input and output ("INOUT").

返回

Nothing.

描述

This method is only needed for DB2, ODBC, or Sybase stored procedures. If you call it for Oracle or Informix stored procedures, it does nothing.

This method provides the procedure name and the parameters for that stored procedure. Stored procedures can accept parameters that are only for input ("IN"), only for output ("OUT"), or for both input and output ("INOUT").

You must create one prototype for each DB2, ODBC, or Sybase stored procedure you use in your application. Additional prototypes for the same stored procedure are ignored.

You can specify an INOUT parameter either as an INOUT or as an OUT parameter. If you use an INOUT parameter of a stored procedure as an OUT parameter, the LiveWire Database Service implicitly passes a NULL value for that parameter.

示例

Assume the inoutdemo stored procedure takes one input parameter and one input/output parameter, as follows:

create procedure inoutdemo ( @inparam int, @inoutparam int output)
as
if ( @inoutparam == null)
@inoutparam = @inparam + 1
else
@inoutparam = @inoutparam + 1 Assume execute the following code and then call outParameters(0), the result will be 101:

database.storedProcArgs("inoutdemo", "IN", "INOUT")
spobj= database.storedProc("inoutdemo", 6, 100);
answer = spobj.outParameters(0);
The value of answer is 101. On the other hand, assume you execute this code:

database.storedProcArgs("inoutdemo", "IN", "OUT")
spobj = database.storedProc("inoutdemo", 6, 100);
answer = spobj.outParameters(0);
In this case, the value of answer is 7.

toString

Returns a string representing the specified object.

方法源 | database
实现版本 | LiveWire 1.0

语法

toString()

参数

 无。

描述

Every object has a toString method that is automatically called when it is to be represented as a text value or when an object is referred to in a string concatenation.

You can use toString within your own code to convert an object into a string, and you can create your own function to be called in place of the default toString method.

This method returns a string of the following format:

db "name" "userName" "dbtype" "serverName" where

name | The name of the database.
userName | The name of the user connected to the database.
dbType | One of ORACLE, SYBASE, INFORMIX, DB2, or ODBC.
serverName | The name of the database server.

The method displays an empty string for any of attributes whose value is unknown.

For information on defining your own toString method, see the Object.toString method.


JavaScript语言参考手册_LiveWire 数据库服务

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

DbPool

Represents a pool of connections to a particular database configuration.

服务器端对象 |
实现版本 | Netscape Server 3.0

To connect to a database, you first create a pool of database connections and then access individual connections as needed. For more information on the general methodology for using DbPool objects, see Writing Server-Side JavaScript Applications.

创建源

The DbPool constructor.

描述

The lifetime of a DbPool object (its scope) varies. Assuming it has been assigned to a variable, a DbPool object can go out of scope at different times:

  • If the variable is a property of the project object (such as project.engconn), then it remains in scope until the application terminates or until you reassign the property to another value or to null.

  • If it is a property of the server object (such as server.engconn), it remains in scope until the server goes down or until you reassign the property to another value or to null.

  • In all other cases, the variable is a property of the request object. In this situation, the variable goes out of scope when control leaves the HTML page or you reassign the property to another value or to null.
It is your responsibility to release all connections and close all cursors, stored procedures, and result sets associated with a DbPool object before that object goes out of scope. Release connections and close the other objects as soon as you are done with them.

If you do not release a connection, it remains bound and is unavailable to the next user until the associated DbPool object goes out of scope. When you do call release to give up a connection, the runtime engine waits until all associated cursors, stored procedures, and result sets are closed before actually releasing the connection. Therefore, you must close those objects when you are done with them.

You can use the prototype property of the DbPool object to add a property to all DbPool instances. If you do so, that addition applies to all DbPool objects running in all applications on your server, not just in the single application that made the change. This allows you to expand the capabilities of this object for your entire server.

属性概览

prototypeAllows the addition of properties to a DbPool object.

方法概览

DbPool | Creates a pool of database Connection objects and optionally connects the objects to a particular configuration of database and user.
connect | Connects the pool to a particular configuration of database and user.
connected | Tests whether the database pool and all of its connections are connected to a database.
connection | Retrieves an available connection from the pool.
disconnect | Disconnects all connections in the pool from the database.
majorErrorCode | Major error code returned by the database server or ODBC.
majorErrorMessage | Major error message returned by database server or ODBC. For server errors, this typically corresponds to the server's SQLCODE.
minorErrorCode | Secondary error code returned by database vendor library.
minorErrorMessage | Secondary message returned by database vendor library.
storedProcArgs | Creates a prototype for a Sybase stored procedure.
toString | Returns a string representing the specified object.

属性

prototype

 Represents the prototype for this class. You can use the prototype to add properties or methods to all instances of a class. For information on prototypes, see Function.prototype.

属性源 | DbPool
实现版本 | LiveWire 1.0

方法

DbPool

 Creates a pool of database Connection objects and optionally connects the objects to a particular configuration of database and user.

方法源 | DbPool
实现版本 | Netscape Server 3.0

语法

new DbPool(); new DbPool (dbtype, serverName, username, password, databaseName); new DbPool (dbtype, serverName, username, password, databaseName, maxConnections); new DbPool (dbtype, serverName, username, password, databaseName, maxConnections, commitflag);

参数

dbtypeDatabase type. One of ORACLE, SYBASE, INFORMIX, DB2, or ODBC.
serverNameName of the database server to which to connect. The server name typically is established when the database is installed and is different for different database types:DB2: Local database alias. On both NT and UNIX, this is set up by the client or the DB2 Command Line Processor.Informix: Informix server. On NT, this is specified with the setnet32 utility; on UNIX, in the sqlhosts file.Oracle: Service. On both NT and UNIX, this specified in the tnsnames.ora file. On NT, you can use the SQL*Net easy configuration to specify it. When your Oracle database server is local, specify the empty string for this argument.ODBC: Data source name. On NT, this is specified in the ODBC Administrator; on UNIX, in the .odbc.ini file. If you are using the Web Server as a user the file .odbc.ini must be in your home directory; if as a system, it must be in the root directory.Sybase: Server name (the DSQUERY parameter). On NT, this is specified with the sqledit utility; on UNIX, with the sybinit utility.If in doubt, see your database or system administrator. For ODBC, this is the name of the ODBC service as specified in Control Panel.
userNameName of the user to connect to the database. Some relational database management systems (RDBMS) require that this be the same as your operating system login name; others maintain their own collections of valid user names. See your system administrator if you are in doubt.
passwordUser's password. If the database does not require a password, use an empty string ("").
databaseNameName of the database to connect to for the given serverName. If your database server supports the notion of multiple databases on a single server, supply the name of the database to use. If it does not, use an empty string (""). For Oracle, ODBC, and DB2, you must always use an empty string.For Oracle, specify this information in the tnsnames.ora file.For ODBC, if you want to connect to a particular database, specify the database name specified in the datasource definition.For DB2, there is no concept of a database name; the database name is always the server name (as specified with serverName).
maxConnections(Optional) Number of connections to be created and cached in the pool. The runtime engine attempts to create as many connections as specified with this parameter. If successful, it stores those connections for later use. If you do not supply this parameter, its value is 1. Remember that your database client license probably specifies a maximum number of connections. Do not set this parameter to a number higher than your license allows. For Sybase, you can have at most 100 connections.If your database client library is not multithreaded, it can only support one connection at a time. In this case, your application performs as though you specified 1 for this parameter. For a current list of which database client libraries are multithreaded, see the Enterprise Server 3.0 Release Notes.
commitFlag(Optional) A Boolean value indicating whether to commit a pending transaction when the connection is released or the object is finalized.(If the transaction is on a single page, the object is finalized at the end of the page. If the transaction spans multiple pages, the object is finalized when the connection returns to the pool.)If this parameter is false, a pending transaction is rolled back. If this parameter is true, a pending transaction if committed. For DbPool, the default value is false; for database, the default value is true. If you specify this parameter, you must also specify the maxConnections parameter.

描述

The first version of this constructor takes no parameters. It instantiates and allocates memory for a DbPool object. This version of the constructor creates and caches one connection. When this connection goes out of scope, pending transactions are rolled back.

The second version of this constructor instantiates a DbPool object and then calls the connect method to establish a database connection. This version of the constructor also creates and caches one connection. When this connection goes out of scope, pending transactions are rolled back.

The third version of this constructor instantiates a DbPool object and then calls the connect method to establish a database connection. In addition, it attempts to create as many connections as specified by the maxConnections parameter. If successful, it stores those connections for later use. If the runtime engine does not obtain the requested connections, it returns an error. When this connection goes out of scope, pending transactions are rolled back.

The fourth version of this constructor does everything the third version does. In addition, the commitflag parameter indicates what to do with pending transactions when the connection goes out of scope. If this parameter is false (the default), a pending transaction is rolled back. If this parameter is true, a pending transaction if committed.

To detect errors, you can use the majorErrorCode method.

If possible, your application should call this constructor and make the database connection on its initial page. Doing so prevents conflicts from multiple client requests trying to manipulate the status of the connections at once.

connect

Connects the pool to a particular configuration of database and user.

方法源 | DbPool
实现版本 | Netscape Server 3.0

语法

connect (dbtype, serverName, username, password, databaseName) connect (dbtype, serverName, username, password, databaseName, maxConnections) connect (dbtype, serverName, username, password, databaseName, maxConnections, commitflag)

参数

dbtypeDatabase type; one of ORACLE, SYBASE, INFORMIX, DB2, or ODBC.
serverNameName of the database server to which to connect. The server name typically is established when the database is installed and is different for different database types:DB2: Local database alias. On both NT and UNIX, this is set up by the client or the DB2 Command Line Processor.Informix: Informix server. On NT, this is specified with the setnet32 utility; on UNIX, in the sqlhosts file.Oracle: Service. On both NT and UNIX, this specified in the tnsnames.ora file. On NT, you can use the SQL*Net easy configuration to specify it. When your Oracle database server is local, specify the empty string for this argument. ODBC: Data source name. On NT, this is specified in the ODBC Administrator; on UNIX, in the .odbc.ini file. If you are using the Web Server as a user the file .odbc.ini must be in your home directory; if as a system, it must be in the root directory.Sybase: Server name (the DSQUERY parameter). On NT, this is specified with the sqledit utility; on UNIX, with the sybinit utility.If in doubt, see your database or system administrator. For ODBC, this is the name of the ODBC service as specified in Control Panel.
userNameName of the user to connect to the database. Some relational database management systems (RDBMS) require that this be the same as your operating system login name; others maintain their own collections of valid user names. See your system administrator if you are in doubt.
passwordUser's password. If the database does not require a password, use an empty string ("").
databaseNameName of the database to connect to for the given serverName. If your database server supports the notion of multiple databases on a single server, supply the name of the database to use. If it does not, use an empty string (""). For Oracle, ODBC, and DB2, you must always use an empty string.For Oracle, specify this information in the tnsnames.ora file.For ODBC, if you want to connect to a particular database, specify the database name specified in the datasource definition.For DB2, there is no concept of a database name; the database name is always the server name (as specified with serverName).
maxConnections(Optional) Number of connections to be created and cached in the pool. The runtime engine attempts to create as many connections as specified with this parameter. If successful, it stores those connections for later use. If you do not supply this parameter, its value is 1. Remember that your database client license probably specifies a maximum number of connections. Do not set this parameter to a number higher than your license allows. For Sybase, you can have at most 100 connections.If your database client library is not multithreaded, it can only support one connection at a time. In this case, your application performs as though you specified 1 for this parameter. For a current list of which database client libraries are multithreaded, see the Enterprise Server 3.0 Release Notes.
commitFlag(Optional) A Boolean value indicating whether to commit a pending transaction when the connection goes out of scope. If this parameter is false, a pending transaction is rolled back. If this parameter is true, a pending transaction if committed. For DbPool, the default value is false; for database, the default value is true. If you specify this parameter, you must also specify the maxConnections parameter.

返回

0 if the call was successful; otherwise, a nonzero status code based on any error message passed by the database. If the method returns a nonzero status code, use the associated majorErrorCode and majorErrorMessage methods to interpret the cause of the error.

描述

When you call this method, the runtime engine first closes and releases any currently open connections. It then reconnects the pool with the new configuration. You should be sure that all connections have been released before calling this method.

The first version of this method creates and caches one connection. When this connection goes out of scope, pending transactions are rolled back.

The second version of this method attempts to create as many connections as specified by the maxConnections parameter. If successful, it stores those connections for later use. If the runtime engine does not obtain the requested connections, it returns an error. When this connection goes out of scope, pending transactions are rolled back.

The third version of this method does everything the second version does. In addition, the commitflag parameter indicates what to do with pending transactions when this connection goes out of scope. If this parameter is false (the default), a pending transaction is rolled back. If this parameter is true, a pending transaction if committed.

示例

The following statement creates four connections to an Informix database named mydb on a server named myserver, with user name SYSTEM and password MANAGER. Pending transactions are rolled back at the end of a client request:

pool.connect("INFORMIX", "myserver", "SYSTEM", "MANAGER", "mydb", 4)

connected

Tests whether the database pool and all of its connections are connected to a database.

方法源 | DbPool
实现版本 | Netscape Server 3.0

语法

connected()

参数

 无。

返回

True if the pool (and hence a particular connection in the pool) is currently connected to a database; otherwise, false.

描述

The connected method indicates whether this object is currently connected to a database.

If this method returns false for a Connection object, you cannot use any other methods of that object. You must reconnect to the database, using the DbPool object, and then get a new Connection object. Similarly, if this method returns false for the database object, you must reconnect before using other methods of that object.

示例

示例 1: The following code fragment checks to see if the connection is currently open. If it's not, it reconnects the pool and reassigns a new value to the myconn variable.

if (!myconn.connected()) {
mypool.connect ("INFORMIX", "myserver", "SYSTEM", "MANAGER", "mydb", 4);
myconn = mypool.connection;
}
示例 2: The following example uses an if condition to determine if an application is connected to a database server. If the application is connected, the isConnectedRoutine function runs; if the application is not connected, the isNotConnected routine runs.

if(database.connected()) {
isConnectedRoutine() }
else {
isNotConnectedRoutine() }

connection

Retrieves an available connection from the pool.

方法源 | DbPool
实现版本 | Netscape Server 3.0

语法

connection (name, timeout)

参数

name | An arbitrary name for the connection. Primarily used for debugging.
timeout | The number of seconds to wait for an available connection before returning. The default is to wait indefinitely. If you specify this parameter, you must also specify the name parameter.

返回

A new Connection object.

disconnect

Disconnects all connections in the pool from the database.

方法源 | DbPool
实现版本 | Netscape Server 3.0

语法

disconnect()

参数

 无。

返回

0 if the call was successful; otherwise, a nonzero status code based on any error message passed by the database. If the method returns a nonzero status code, use the associated majorErrorCode and majorErrorMessage methods to interpret the cause of the error.

描述

For the DbPool object, before calling the disconnect method, you must first call the release method for all connections in this database pool. Otherwise, the connection is still considered in use by the system, so the disconnect waits until all connections are released.

After disconnecting from a database, the only methods of this object you can use are connect and connected.

示例

The following example uses an if condition to determine if an application is connected to a database server. If the application is connected, the application calls the disconnect method; if the application is not connected, the isNotConnected routine runs.

if(database.connected()) {
database.disconnect() }
else {
isNotConnectedRoutine() }

majorErrorCode

Major error code returned by the database server or ODBC.

方法源 | DbPool
实现版本 | Netscape Server 3.0

语法

majorErrorCode()

参数

 无。

返回

The result returned by this method depends on the database server being used:

  • Informix: the Informix error code.

  • Oracle: the code as reported by Oracle Call-level Interface (OCI).

  • Sybase: the DB-Library error number or the SQL server message number.

描述

 SQL statements can fail for a variety of reasons, including referential integrity constraints, lack of user privileges, record or 表 locking in a multiuser database, and so on. When an action fails, the database server returns an error message indicating the reason for failure. The LiveWire Database Service provides two ways of getting error information: from the status code returned by various methods or from special properties containing error messages and codes.

Status codes are integers between 0 and 27, with 0 indicating a successful execution of the statement and other numbers indicating an error, as shown in

表 10.3 Database status codes.
Status Code | Explanation | Status Code | Explanation
0 | No error | 14 | Null reference parameter
1 | Out of memory | 15 | Connection object not found
2 | Object never initialized | 16 | Required information is missing
3 | Type conversion error | 17 | Object cannot support multiple readers
4 | Database not registered | 18 | Object cannot support deletions
5 | Error reported by server | 19 | Object cannot support insertions
6 | Message from server | 20 | Object cannot support updates
7 | Error from vendor's library | 21 | Object cannot support updates
8 | Lost connection | 22 | Object cannot support indices
9 | End of fetch | 23 | Object cannot be dropped
10 | Invalid use of object | 24 | Incorrect connection supplied
11 | Column does not exist | 25 | Object cannot support privileges
12 | Invalid positioning within object (bounds error) | 26 | Object cannot support cursors
13 | Unsupported feature | 27 | Unable to open
表 10.3.

示例

This example updates the rentals 表 within a transaction. The updateRow method assigns a database status code to the statusCode variable to indicate whether the method is successful.

If updateRow succeeds, the value of statusCode is 0, and the transaction is committed. If updateRow returns a statusCode value of either five or seven, the values of majorErrorCode, majorErrorMessage, minorErrorCode, and minorErrorMessage are displayed. If statusCode is set to any other value, the errorRoutine function is called.

database.beginTransaction()
statusCode = cursor.updateRow("rentals")
if (statusCode == 0) {
database.commitTransaction()
}
if (statusCode == 5 || statusCode == 7) {
write("The operation failed to complete.<BR>"
write("Contact your system administrator with the following:<P>"
write("The value of statusCode is " + statusCode + "<BR>")
write("The value of majorErrorCode is " +
database.majorErrorCode() + "<BR>")
write("The value of majorErrorMessage is " +
database.majorErrorMessage() + "<BR>")
write("The value of minorErrorCode is " +
database.minorErrorCode() + "<BR>")
write("The value of minorErrorMessage is " +
database.minorErrorMessage() + "<BR>")
database.rollbackTransaction()
}
else {
errorRoutine()
}

majorErrorMessage

Major error message returned by database server or ODBC. For server errors, this typically corresponds to the server's SQLCODE.

方法源 | DbPool
实现版本 | Netscape Server 3.0

语法

majorErrorMessage()

参数

 无。

返回

A string describing that depends on the database server:

  • Informix: "Vendor Library Error: string," where string is the error text from Informix.

  • Oracle: "Server Error: string," where string is the translation of the return code supplied by Oracle.

  • Sybase: "Vendor Library Error: string," where string is the error text from DB-Library or "Server Error string," where string is text from the SQL server, unless the severity and message number are both 0, in which case it returns just the message text.

描述

 SQL statements can fail for a variety of reasons, including referential integrity constraints, lack of user privileges, record or 表 locking in a multiuser database, and so on. When an action fails, the database server returns an error message indicating the reason for failure. The LiveWire Database Service provides two ways of getting error information: from the status code returned by connection and DbPool methods or from special connection or DbPool properties containing error messages and codes.

示例

See DbPool.majorErrorCode.

minorErrorCode

Secondary error code returned by database vendor library.

方法源 | DbPool
实现版本 | Netscape Server 3.0

语法

minorErrorCode()

参数

 无。

返回

The result returned by this method depends on the database server:

  • Informix: the ISAM error code, or 0 if there is no ISAM error.

  • Oracle: the operating system error code as reported by OCI.

  • Sybase: the severity level, as reported by DB-Library or the severity level, as reported by the SQL server.

minorErrorMessage

 Secondary message returned by database vendor library.

方法源 | DbPool
实现版本 | Netscape Server 3.0

语法

minorErrorMessage()

参数

 无。

返回

The string returned by this method depends on the database server:

  • Informix: "ISAM Error: string," where string is the text of the ISAM error code from Informix, or an empty string if there is no ISAM error.

  • Oracle: the Oracle server name.

  • Sybase: the operating system error text, as reported by DB-Library or the SQL server name.

storedProcArgs

 Creates a prototype for a DB2, ODBC, or Sybase stored procedure.

方法源 | DbPool
实现版本 | Netscape Server 3.0

语法

storedProcArgs (procName, type1, ..., typeN)

参数

procName | The name of the procedure.
type1, ..., typeN | Each typeI is one of: "IN", "OUT", or "INOUT" Specifies the type of each parameter: input ("IN"), output ("OUT"), or both input and output ("INOUT").

返回

Nothing.

描述

This method is only for Sybase stored procedures.

This method provides the procedure name and the parameters for that stored procedure. Sybase stored procedures can accept parameters that are only for input ("IN"), only for output ("OUT"), or for both input and output ("INOUT").

You must create one prototype for each Sybase stored procedure you use in your application. Additional prototypes for the same stored procedure are ignored.

You can specify an INOUT parameter either as an INOUT or as an OUT parameter. If you use an INOUT parameter of a stored procedure as an OUT parameter, the LiveWire Database Service implicitly passes a NULL value for that parameter.

示例

Assume the inoutdemo stored procedure takes one input parameter and one input/output parameter, as follows:

create procedure inoutdemo ( @inparam int, @inoutparam int output)
as
if ( @inoutparam == null)
@inoutparam = @inparam + 1
else
@inoutparam = @inoutparam + 1 Assume execute the following code and then call outParameters(0), the result will be 101:

database.storedProcArgs("inoutdemo", "IN", "INOUT")
spobj= database.storedProc("inoutdemo", 6, 100);
answer = spobj.outParameters(0);
The value of answer is 101. On the other hand, assume you execute this code:

database.storedProcArgs("inoutdemo", "IN", "OUT")
spobj = database.storedProc("inoutdemo", 6, 100);
answer = spobj.outParameters(0);
In this case, the value of answer is 7.

toString

Returns a string representing the specified object.

方法源 | DbPool
实现版本 | Netscape Server 3.0

语法

toString()

参数

 无。

描述

Every object has a toString method that is automatically called when it is to be represented as a text value or when an object is referred to in a string concatenation.

You can use toString within your own code to convert an object into a string, and you can create your own function to be called in place of the default toString method.

This method returns a string of the following format:

db "name" "userName" "dbtype" "serverName" where

name | The name of the database.
userName | The name of the user connected to the database.
dbType | One of ORACLE, SYBASE, INFORMIX, DB2, or ODBC.
serverName | The name of the database server.

The method displays an empty string for any of attributes whose value is unknown.

For information on defining your own toString method, see the Object.toString method.


JavaScript语言参考手册_LiveWire 数据库服务

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

Connection

Represents a single database connection from a pool of connections.

服务器端对象 |
实现版本 | Netscape Server 3.0

创建源

The DbPool.connection method. You do not call a connection constructor directly. Once you have a Connection object, you use it for your interactions with the database.

描述

You can use the prototype property of the Connection class to add a property to all Connection instances. If you do so, that addition applies to all Connection objects running in all applications on your server, not just in the single application that made the change. This allows you to expand the capabilities of this object for your entire server.

属性概览

prototypeAllows the addition of properties to a Connection object.

方法概览

beginTransaction | Begins a new SQL transaction.
commitTransaction | Commits the current transaction.
connected | Tests whether the database pool (and hence this connection) is connected to a database.
cursor | Creates a database cursor for the specified SQL SELECT statement.
execute | Performs the specified SQL statement. Use for SQL statements other than queries.
majorErrorCode | Major error code returned by the database server or ODBC.
majorErrorMessage | Major error message returned by database server or ODBC.
minorErrorCode | Secondary error code returned by database vendor library.
minorErrorMessage | Secondary message returned by database vendor library.
release | Releases the connection back to the database pool.
rollbackTransaction | Rolls back the current transaction.
SQL表 | Displays query results. Creates an HTML 表 for results of an SQL SELECT statement.
storedProc | Creates a stored-procedure object and runs the specified stored procedure.
toString | Returns a string representing the specified object.

属性

prototype

 Represents the prototype for this class. You can use the prototype to add properties or methods to all instances of a class. For information on prototypes, see Function.prototype.

属性源 | Connection
实现版本 | LiveWire 1.0

方法

beginTransaction

 Begins a new SQL transaction.

方法源 | Connection
实现版本 | Netscape Server 3.0

语法

beginTransaction()

参数

 无。

返回

0 if the call was successful; otherwise, a nonzero status code based on any error message passed by the database. If the method returns a nonzero status code, use the associated majorErrorCode and majorErrorMessage methods to interpret the cause of the error.

描述

All subsequent actions that modify the database are grouped with this transaction, known as the current transaction.

For the database object, the scope of a transaction is limited to the current request (HTML page) in the application. If the application exits the page before calling the commitTransaction or rollbackTransaction method, then the transaction is automatically either committed or rolled back, based on the setting of the commitflag parameter when the connection was established. This parameter is provided when you make the connection by calling database.connect.

For Connection objects, the scope of a transaction is limited to the lifetime of that object. If the connection is released or the pool of connections is closed before calling the commitTransaction or rollbackTransaction method, then the transaction is automatically either committed or rolled back, based on the setting of the commitflag parameter when the connection was established. This parameter is provided when you make the connection by calling the connect method or in the DbPool constructor.

If there is no current transaction (that is, if the application has not called beginTransaction), calls to commitTransaction and rollbackTransaction are ignored.

The LiveWire Database Service does not support nested transactions. If you call beginTransaction when a transaction is already open (that is, you've called beginTransaction and have yet to commit or roll back that transaction), you'll get an error message.

示例

This example updates the rentals 表 within a transaction. The values of customerID and videoID are passed into the cursor method as properties of the request object. When the videoReturn Cursor object opens, the next method navigates to the only record in the answer set and updates the value in the returnDate field.

The variable x is assigned a database status code to indicate if the updateRow method is successful. If updateRow succeeds, the value of x is 0, and the transaction is committed; otherwise, the transaction is rolled back.

// Begin a transaction
database.beginTransaction();
// Create a Date object with the value of today's date
today = new Date();
// Create a Cursor with the rented video in the answer set
videoReturn = database.Cursor("SELECT * FROM rentals WHERE
customerId = " + request.customerID + " AND
videoId = " + request.videoID, true);
// Position the pointer on the first row of the Cursor
// and update the row
videoReturn.next()
videoReturn.returndate = today;
x = videoReturn.updateRow("rentals");
// End the transaction by committing or rolling back
if (x == 0) {
database.commitTransaction() }
else {
database.rollbackTransaction() }
// Close the Cursor
videoReturn.close();

commitTransaction

Commits the current transaction

方法源 | Connection
实现版本 | Netscape Server 3.0

语法

commitTransaction()

参数

 无。

返回

0 if the call was successful; otherwise, a nonzero status code based on any error message passed by the database. If the method returns a nonzero status code, use the associated majorErrorCode and majorErrorMessage methods to interpret the cause of the error.

描述

This method attempts to commit all actions since the last call to beginTransaction.

For the database object, the scope of a transaction is limited to the current request (HTML page) in the application. If the application exits the page before calling the commitTransaction or rollbackTransaction method, then the transaction is automatically either committed or rolled back, based on the setting of the commitflag parameter when the connection was established. This parameter is provided when you make the connection with the database or DbPool object.

For Connection objects, the scope of a transaction is limited to the lifetime of that object. If the connection is released or the pool of connections is closed before calling the commitTransaction or rollbackTransaction method, then the transaction is automatically either committed or rolled back, based on the commitFlag value.

If there is no current transaction (that is, if the application has not called beginTransaction), calls to commitTransaction and rollbackTransaction are ignored.

The LiveWire Database Service does not support nested transactions. If you call beginTransaction when a transaction is already open (that is, you've called beginTransaction and have yet to commit or roll back that transaction), you'll get an error message.

connected

Tests whether the database pool and all of its connections are connected to a database.

方法源 | Connection
实现版本 | Netscape Server 3.0

语法

connected()

参数

 无。

返回

True if the pool (and hence a particular connection in the pool) is currently connected to a database; otherwise, false.

描述

The connected method indicates whether this object is currently connected to a database.

If this method returns false for a Connection object, you cannot use any other methods of that object. You must reconnect to the database, using the DbPool object, and then get a new Connection object. Similarly, if this method returns false for the database object, you must reconnect before using other methods of that object.

示例

示例 1: The following code fragment checks to see if the connection is currently open. If it's not, it reconnects the pool and reassigns a new value to the myconn variable.

if (!myconn.connected()) {
mypool.connect ("INFORMIX", "myserver", "SYSTEM", "MANAGER", "mydb", 4);
myconn = mypool.connection;
}
示例 2: The following example uses an if condition to determine if an application is connected to a database server. If the application is connected, the isConnectedRoutine function runs; if the application is not connected, the isNotConnected routine runs.

if(database.connected()) {
isConnectedRoutine() }
else {
isNotConnectedRoutine() }

cursor

Creates a Cursor object.

方法源 | Connection
实现版本 | Netscape Server 3.0

语法

cursor("sqlStatement",upda表)

参数

sqlStatement | A JavaScript string representing a SQL SELECT statement supported by the database server.
upda表 | (Optional) A Boolean parameter indicating whether or not the cursor is upda表.

返回

A new Cursor object.

描述

The cursor method creates a Cursor object that contains the rows returned by a SQL SELECT statement. The SELECT statement is passed to the cursor method as the sqlStatement argument. If the SELECT statement does not return any rows, the resulting Cursor object has no rows. The first time you use the next method on the object, it returns false.

You can perform the following tasks with the Cursor object:

  • Modify data in a server 表.
    •
  • Navigate in a server 表.
    •
  • Customize the display of the virtual 表 returned by a database query.
    •
  • Run stored procedures.
The cursor method does not automatically display the returned data. To display this data, you must create custom HTML code. This HTML code may display the rows in an HTML 表, as shown in Example 3. The SQL表 method is an easier way to display the output of a database query, but you cannot navigate, modify data, or control the format of the output.

The optional parameter upda表 specifies whether you can modify the Cursor object you create with the cursor method. To create a Cursor object you can modify, specify upda表 as true. If you do not specify a value for the upda表 parameter, it is false by default.

If you create an upda表 Cursor object, the answer set returned by the sqlStatement parameter must be upda表. For example, the SELECT statement in the sqlStatement parameter cannot contain a GROUP BY clause; in addition, the query usually must retrieve key values from a 表. For more information on constructing upda表 queries, consult your database vendor's documentation.

示例

示例 1. The following example creates the upda表 cursor custs and returns the columns ID, CUST_NAME, and CITY from the customer 表:

custs = database.Cursor("select id, cust_name, city from customer", true) 示例 2. You can construct the SELECT statement with the string concatenation operator (+) and string variables such as client or request property values, as shown in the following example:

custs = database.Cursor("select * from customer
where customerID = " + request.customerID); 示例 3. The following example demonstrates how to format the answer set returned by the cursor method as an HTML 表. This example first creates Cursor object named videoSet and then displays two columns of its data (videoSet.title and videoSet.synopsis).

// Create the videoSet Cursor
<SERVER>
videoSet = database.cursor("select * from videos
where videos.numonhand > 0 order by title");
</SERVER> // Begin creating an HTML 表 to contain the answer set
// Specify titles for the two columns in the answer set
<表 BORDER>
<CAPTION> Videos on Hand </CAPTION>
<TR>
<TH>Title</TH>
<TH>Synopsis</TH>
</TR> // Use a while loop to iterate over each row in the cursor
<SERVER>
while(videoSet.next()) {
</SERVER> // Use write statements to display the data in both columns
<TR>
<TH><A HREF=\Q"rent.html?videoID="+videoSet.id\Q>
<SERVER>write(videoSet.title)</SERVER></A></TH>
<TD><SERVER>write(videoSet.synopsis)</SERVER></TD>
</TR> // End the while loop
<SERVER>
}
</SERVER> // End the HTML 表
</表> The values in the videoSet.title column are displayed within the A tag so a user can click them as links. When a user clicks a title, the rent.html page opens and the column value videoSet.id is passed to it as the value of request.videoID.

参看

Connection.SQL表, Connection.cursor

execute

Performs the specified SQL statement. Use for SQL statements other than queries.

方法源 | Connection
实现版本 | Netscape Server 3.0

语法

execute (stmt)

参数

stmtA string representing the SQL statement to execute.

返回

0 if the call was successful; otherwise, a nonzero status code based on any error message passed by the database. If the method returns a nonzero status code, use the associated majorErrorCode and majorErrorMessage methods to interpret the cause of the error.

描述

This method enables an application to execute any data definition language (DDL) or data manipulation language (DML) SQL statement supported by the database server that does not return a Cursor, such as CREATE, ALTER, or DROP.

Each database supports a standard core of DDL and DML statements. In addition, they may each also support DDL and DML statements specific to that database vendor. You can use execute to call any of those statements. However, each database vendor may also provide functions you can use with the database that are not DDL or DML statements. You cannot use execute to call those functions. For example, you cannot call the Oracle describe function or the Informix load function from the execute method.

Although technically you can use execute to perform data modification (INSERT, UPDATE, and DELETE statements), you should instead use Cursor objects. This makes your application more database-independent. Cursors also provide support for binary large object (BLOb) data.

When using the execute method, your SQL statement must strictly conform to the语法 requirements of the database server. For example, some servers require each SQL statement to be terminated by a semicolon. See your server documentation for more information.

If you have not explicitly started a transaction, the single statement is automatically committed.

示例

In the following example, the execute method is used to delete a customer from the customer 表. customer.ID represents the unique ID of a customer that is in the ID column of the customer 表. The value for customer.ID is passed into the DELETE statement as the value of the ID property of the request object.

if(request.ID != null) {
database.execute("delete from customer
where customer.ID = " + request.ID)
}

majorErrorCode

Major error code returned by the database server or ODBC.

方法源 | Connection
实现版本 | Netscape Server 3.0

语法

majorErrorCode()

参数

 无。

返回

The result returned by this method depends on the database server being used:

  • Informix: the Informix error code.

  • Oracle: the code as reported by Oracle Call-level Interface (OCI).

  • Sybase: the DB-Library error number or the SQL server message number.

描述

 SQL statements can fail for a variety of reasons, including referential integrity constraints, lack of user privileges, record or 表 locking in a multiuser database, and so on. When an action fails, the database server returns an error message indicating the reason for failure. The LiveWire Database Service provides two ways of getting error information: from the status code returned by various methods or from special properties containing error messages and codes.

Status codes are integers between 0 and 27, with 0 indicating a successful execution of the statement and other numbers indicating an error, as shown in 表 10.4.

表 10.4 Database status codes.
Status Code | Explanation | Status Code | Explanation
0 | No error | 14 | Null reference parameter
1 | Out of memory | 15 | Connection object not found
2 | Object never initialized | 16 | Required information is missing
3 | Type conversion error | 17 | Object cannot support multiple readers
4 | Database not registered | 18 | Object cannot support deletions
5 | Error reported by server | 19 | Object cannot support insertions
6 | Message from server | 20 | Object cannot support updates
7 | Error from vendor's library | 21 | Object cannot support updates
8 | Lost connection | 22 | Object cannot support indices
9 | End of fetch | 23 | Object cannot be dropped
10 | Invalid use of object | 24 | Incorrect connection supplied
11 | Column does not exist | 25 | Object cannot support privileges
12 | Invalid positioning within object (bounds error) | 26 | Object cannot support cursors
13 | Unsupported feature | 27 | Unable to open

示例

This example updates the rentals 表 within a transaction. The updateRow method assigns a database status code to the statusCode variable to indicate whether the method is successful.

If updateRow succeeds, the value of statusCode is 0, and the transaction is committed. If updateRow returns a statusCode value of either five or seven, the values of majorErrorCode, majorErrorMessage, minorErrorCode, and minorErrorMessage are displayed. If statusCode is set to any other value, the errorRoutine function is called.

database.beginTransaction()
statusCode = cursor.updateRow("rentals")
if (statusCode == 0) {
database.commitTransaction()
}
if (statusCode == 5 || statusCode == 7) {
write("The operation failed to complete.<BR>"
write("Contact your system administrator with the following:<P>"
write("The value of statusCode is " + statusCode + "<BR>")
write("The value of majorErrorCode is " +
database.majorErrorCode() + "<BR>")
write("The value of majorErrorMessage is " +
database.majorErrorMessage() + "<BR>")
write("The value of minorErrorCode is " +
database.minorErrorCode() + "<BR>")
write("The value of minorErrorMessage is " +
database.minorErrorMessage() + "<BR>")
database.rollbackTransaction()
}
else {
errorRoutine()
}

majorErrorMessage

Major error message returned by database server or ODBC. For server errors, this typically corresponds to the server's SQLCODE.

方法源 | Connection
实现版本 | Netscape Server 3.0

语法

majorErrorMessage()

参数

 无。

返回

A string describing that depends on the database server:

  • Informix: "Vendor Library Error: string," where string is the error text from Informix.

  • Oracle: "Server Error: string," where string is the translation of the return code supplied by Oracle.

  • Sybase: "Vendor Library Error: string," where string is the error text from DB-Library or "Server Error string," where string is text from the SQL server, unless the severity and message number are both 0, in which case it returns just the message text.

描述

 SQL statements can fail for a variety of reasons, including referential integrity constraints, lack of user privileges, record or 表 locking in a multiuser database, and so on. When an action fails, the database server returns an error message indicating the reason for failure. The LiveWire Database Service provides two ways of getting error information: from the status code returned by connection and DbPool methods or from special connection or DbPool properties containing error messages and codes.

示例

See Connection.majorErrorCode.

minorErrorCode

Secondary error code returned by database vendor library.

方法源 | Connection
实现版本 | Netscape Server 3.0

语法

minorErrorCode()

参数

 无。

返回

The result returned by this method depends on the database server:

  • Informix: the ISAM error code, or 0 if there is no ISAM error.

  • Oracle: the operating system error code as reported by OCI.

  • Sybase: the severity level, as reported by DB-Library or the severity level, as reported by the SQL server.

minorErrorMessage

 Secondary message returned by database vendor library.

方法源 | Connection
实现版本 | Netscape Server 3.0

语法

minorErrorMessage()

参数

 无。

返回

The string returned by this method depends on the database server:

  • Informix: "ISAM Error: string," where string is the text of the ISAM error code from Informix, or an empty string if there is no ISAM error.

  • Oracle: the Oracle server name.

  • Sybase: the operating system error text, as reported by DB-Library or the SQL server name.

release

 Releases the connection back to the database pool.

方法源 | Connection
实现版本 | Netscape Server 3.0

语法

release()

参数

 无。

返回

0 if the call was successful; otherwise, a nonzero status code based on any error message passed by the database. If the method returns a nonzero status code, use the associated majorErrorCode and majorErrorMessage methods to interpret the cause of the error.

描述

Before calling the release method, you should close all open cursors. When you call the release method, the runtime engine waits until all cursors have been closed and then returns the connection to the database pool. The connection is then available to the next user.

If you don't call the release method, the connection remains unavailable until the object goes out of scope. Assuming the object has been assigned to a variable, it can go out of scope at different times:

  • If the variable is a property of the project object (such as project.engconn), then it remains in scope until the application terminates.

  • If it is a property of the server object (such as server.engconn), it does not go out of scope until the server goes down. You rarely want to have a connection last the lifetime of the server.

  • In all other cases, the variable is a property of the client request. In this situation, the variable goes out of scope when the JavaScript finalize method is called; that is, when control leaves the HTML page.
You must call the release method for all connections in a database pool before you can call the DbPool object's disconnect method. Otherwise, the connection is still considered in use by the runtime engine, so the disconnect waits until all connections are released.

rollbackTransaction

Rolls back the current transaction.

方法源 | Connection
实现版本 | Netscape Server 3.0

语法

rollbackTransaction()

参数

 无。

返回

0 if the call was successful; otherwise, a nonzero status code based on any error message passed by the database. If the method returns a nonzero status code, use the associated majorErrorCode and majorErrorMessage methods to interpret the cause of the error.

描述

This method will undo all modifications since the last call to beginTransaction.

For the database object, the scope of a transaction is limited to the current request (HTML page) in the application. If the application exits the page before calling the commitTransaction or rollbackTransaction method, then the transaction is automatically either committed or rolled back, based on the setting of the commitflag parameter when the connection was established. This parameter is provided when you make the connection with the database or DbPool object.

For Connection objects, the scope of a transaction is limited to the lifetime of that object. If the connection is released or the pool of connections is closed before calling the commitTransaction or rollbackTransaction method, then the transaction is automatically either committed or rolled back, based on the commitFlag value.

If there is no current transaction (that is, if the application has not called beginTransaction), calls to commitTransaction and rollbackTransaction are ignored.

The LiveWire Database Service does not support nested transactions. If you call beginTransaction when a transaction is already open (that is, you've called beginTransaction and have yet to commit or roll back that transaction), you'll get an error message.

SQL表

Displays query results. Creates an HTML 表 for results of an SQL SELECT statement.

方法源 | Connection
实现版本 | Netscape Server 3.0

语法

SQL表 (stmt)

参数

stmtA string representing an SQL SELECT statement.

返回

A string representing an HTML 表, with each row and column in the query as a row and column of the 表.

描述

Although SQL表 does not give explicit control over how the output is formatted, it is the easiest way to display query results. If you want to customize the appearance of the output, use a Cursor object to create your own display function.

Note

Every Sybase 表 you use with a cursor must have a unique index.

示例

If connobj is a Connection object and request.sql contains an SQL query, then the following JavaScript statements display the result of the query in a 表:

write(request.sql)
connobj.SQL表(request.sql) The first line simply displays the SELECT statement, and the second line displays the results of the query. This is the first part of the HTML generated by these statements:

select * from videos
<表 BORDER>
<TR>
<TH>title</TH>
<TH>id</TH>
<TH>year</TH>
<TH>category</TH>
<TH>quantity</TH>
<TH>numonhand</TH>
<TH>synopsis</TH>
</TR>
<TR>
<TD>A Clockwork Orange</TD>
<TD>1</TD>
<TD>1975</TD>
<TD>Science Fiction</TD>
<TD>5</TD>
<TD>3</TD>
<TD> Little Alex, played by Malcolm Macdowell,
and his droogies stop by the Miloko bar for a
refreshing libation before a wild night on the town.
</TD>
</TR>
<TR>
<TD>Sleepless In Seattle</TD>
... As this example illustrates, SQL表 generates an HTML 表, with column headings for each column in the database 表 and a row in the 表 for each row in the database 表.

storedProc

Creates a stored-procedure object and runs the specified stored procedure.

方法源 | Connection
实现版本 | Netscape Server 3.0

语法

storedwProc (procName, inarg1, inarg2, ..., inargN)

参数

procName | A string specifying the name of the stored procedure to run.
inarg1, ..., inargN | The input parameters to be passed to the procedure, separated by commas.

返回

A new Stproc object.

描述

The scope of the stored-procedure object is a single page of the application. In other words, all methods to be executed for any instance of storedProc must be invoked on the same application page as the page on which the object is created.

When you create a stored procedure, you can specify default values for any of the parameters. Then, if a parameter is not included when the stored procedure is executed, the procedure uses the default value. However, when you call a stored procedure from a server-side JavaScript application, you must indicate that you want to use the default value by typing "/Default/" in place of the parameter. (Remember that JavaScript is case sensitive.) For example: spObj = connobj.storedProc ("newhire", "/Default/", 3)

toString

Returns a string representing the specified object.

方法源 | Connection
实现版本 | Netscape Server 3.0

语法

toString()

参数

 无。

描述

Every object has a toString method that is automatically called when it is to be represented as a text value or when an object is referred to in a string concatenation.

You can use toString within your own code to convert an object into a string, and you can create your own function to be called in place of the default toString method.

This method returns a string of the following format:

db "name" "userName" "dbtype" "serverName" where

name | The name of the database.
userName | The name of the user connected to the database.
dbType | One of ORACLE, SYBASE, INFORMIX, DB2, or ODBC.
serverName | The name of the database server.

The method displays an empty string for any of attributes whose value is unknown.

For information on defining your own toString method, see the Object.toString method.


JavaScript语言参考手册_LiveWire 数据库服务

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

Stproc

 Represents a call to a database stored procedure.

服务器端对象 |
实现版本 | Netscape Server 3.0

创建源

The storedProc method of the database object or of a Connection object. You do not call a Stproc constructor.

描述

When finished with a Stproc object, use the close method to close it and release the memory it uses. If you release a connection that has an open stored procedure, the runtime engine waits until the stored procedure is closed before actually releasing the connection.

If you do not explicitly close a stored procedure with the close method, the JavaScript runtime engine on the server automatically tries to close all open stored procedures when the associated database or Connection object goes out of scope. This can tie up system resources unnecessarily. It can also lead to unpredic表 results.

You can use the prototype property of the Stproc class to add a property to all Stproc instances. If you do so, that addition applies to all Stproc objects running in all applications on your server, not just in the single application that made the change. This allows you to expand the capabilities of this object for your entire server.

属性概览

prototypeAllows the addition of properties to a Stproc object.

方法概览

close | Closes a stored-procedure object.
outParamCount | Returns the number of output parameters returned by a stored procedure.
outParameters | Returns the value of the specified output parameter.
resultSet | Returns a new result set object.
returnValue | Returns the return value for the stored procedure.

属性

prototype

 Represents the prototype for this class. You can use the prototype to add properties or methods to all instances of a class. For information on prototypes, see Function.prototype.

属性源 | Stproc
实现版本 | LiveWire 1.0

方法

close

 Closes the stored procedure and frees the allocated memory.

方法源 | Stproc
实现版本 | Netscape Server 3.0

语法

close()

参数

 无。

返回

0 if the call was successful; otherwise, a nonzero status code based on any error message passed by the database. If the method returns a nonzero status code, use the associated majorErrorCode and majorErrorMessage methods to interpret the cause of the error.

描述

The close method closes a stored procedure and releases the memory it uses. If you do not explicitly close a stored procedure with the close method, the JavaScript runtime engine on the server automatically closes it when the corresponding client object goes out of scope.

outParamCount

Returns the number of output parameters returned by a stored procedure.

方法源 | Stproc
实现版本 | Netscape Server 3.0

语法

outParamCount()

参数

 无。

返回

The number of output parameters for the stored procedure. Informix stored procedures do not have output parameters. Therefore for Informix, this method always returns 0. You should always call this method before calling outParameters, to ensure that the stored procedure has output parameters.

outParameters

Returns the value of the specified output parameter.

方法源 | Stproc
实现版本 | Netscape Server 3.0

语法

outParameters (n)

参数

nZero-based ordinal for the output parameter to return.

返回

The value of the specified output parameter. This can be a string, number, double, or object.

描述

Do not use this method for Informix stored procedures, because they do not have output parameters.

You should always call the outParamCount method before you call this method. If outParamCount returns 0, the stored procedure has no output parameters. In this situation, do not call this method.

You must retrieve result set objects before you call this method. Once you call this method, you can't get any more data from a result set, and you can't get any additional result sets.

resultSet

Returns a new result set object.

方法源 | Stproc
实现版本 | Netscape Server 3.0

语法

resultSet ()

参数

 无。

描述

Running a stored procedure can create 0 or more result sets. You access the result sets in turn by repeated calls to the resultSet method. See the描述 of the Resultset for restrictions on when you can use this method access the result sets for a stored procedure.

spobj = connobj.storedProc("getcusts");
// Creates a new result set object
resobj = spobj.resultSet();

returnValue

Returns the return value for the stored procedure.

方法源 | Stproc
实现版本 | Netscape Server 3.0

语法

returnValue()

参数

 无。

返回

For Sybase, this method always returns the return value of the stored procedure.

For Oracle, this method returns null if the stored procedure did not return a value or the return value of the stored procedure.

For Informix, DB2, and ODBC, this method always returns null.

描述

You must retrieve result set objects before you call this method. Once you call this method, you can't get any more data from a result set, and you can't get any additional result sets.


JavaScript语言参考手册_LiveWire 数据库服务

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

Resultset

 Represents a virtual 表 created by executing a stored procedure.

服务器端对象 |
实现版本 | Netscape Server 3.0

创建源

The resultSet method of a Stproc object. The Resultset object does not have a constructor.

描述

For Sybase, Oracle, ODBC, and DB2 stored procedures, the stored-procedure object has one result set object for each SELECT statement executed by the stored procedure. For Informix stored procedures, the stored-procedure object always has one result set object.

A result set has a property for each column in the SELECT statement used to generate the result set. For Sybase, Oracle, and ODBC stored procedures, you can refer to these properties by the name of the column in the virtual 表. For Informix and DB2 stored procedures, the columns are not named. For these databases, you must use a numeric index to refer to the column.

Result set objects are not valid indefinitely. In general, once a stored procedure starts, no interactions are allowed between the database client and the database server until the stored procedure has completed. In particular, there are three circumstances that cause a result set to be invalid:

  1. If you create a result set as part of a transaction, you must finish using the result set during that transaction. Once you either commit or rollback the transaction, you can't get any more data from a result set, and you can't get any additional result sets. For example, the following code is illegal: database.beginTransaction();
    spobj = database.storedProc("getcusts");
    resobj = spobj.resultSet();
    database.commitTransaction();
    /* Illegal! Result set no longer valid! */
    col1 = resobj[0];

  2. You must retrieve result set objects before you call a stored-procedure object's returnValue or outParameters methods. Once you call either of these methods, you can't get any more data from a result set, and you can't get any additional result sets. spobj = database.storedProc("getcusts");
    resobj = spobj.resultSet();
    retval = spobj.returnValue();
    /* Illegal! Result set no longer valid! */
    col1 = resobj[0];

  3. Similarly, you must retrieve result set objects before you call the associated Connection object's cursor or SQLTable method. For example, the following code is illegal:

spobj = database.storedProc("getcusts");
cursobj = database.cursor("SELECT * FROM ORDERS;");
/* Illegal! The result set is no longer available! */
resobj = spobj.resultSet();
col1 = resobj[0];
When finished with a Resultset object, use the close method to close it and release the memory it uses. If you release a connection that has an open result set, the runtime engine waits until the result set is closed before actually releasing the connection.

If you do not explicitly close a result set with the close method, the JavaScript runtime engine on the server automatically tries to close all open result sets when the associated database or DbPool object goes out of scope. This can tie up system resources unnecessarily. It can also lead to unpredic表 results.

You can use the prototype property of the Resultset class to add a property to all Resultset instances. If you do so, that addition applies to all Resultset objects running in all applications on your server, not just in the single application that made the change. This allows you to expand the capabilities of this object for your entire server.

属性概览

prototypeAllows the addition of properties to a Resultset object.

方法概览

close | Closes a result set object.
columnName | Returns the name of a column in the result set.
columns | Returns the number of columns in the result set.
next | Moves the current row to the next row in the result set.

示例

Assume you have the following Oracle stored procedure:

create or replace package timpack
as type timcurtype is ref cursor return customer%rowtype;
type timrentype is ref cursor return rentals%rowtype;
end timpack;
create or replace procedure timset4(timrows1 in out timpack.timcurtype, timrows in out timpack.timrentype)
as begin
open timrows for select * from rentals;
open timrows1 for select * from customer;
end timset4;
Running this stored procedure creates two result sets you can access. In the following code fragment the resobj1 result set has rows returned by the timrows ref cursor and the resobj2 result set has the rows returned by the timrows1 ref cursor.

spobj = database.storedProc("timset4");
resobj1 = spobj.resultSet();
resobj2 = spobj.resultSet();

属性

prototype

 Represents the prototype for this class. You can use the prototype to add properties or methods to all instances of a class. For information on prototypes, see Function.prototype.

属性源 | Resultset
实现版本 | LiveWire 1.0

方法

close

 Closes the result set and frees the allocated memory.

方法源 | Resultset
实现版本 | Netscape Server 3.0

语法

close()

参数

 无。

返回

0 if the call was successful; otherwise, a nonzero status code based on any error message passed by the database. If the method returns a nonzero status code, use the associated majorErrorCode and majorErrorMessage methods to interpret the cause of the error.

描述

The close method closes a cursor or result set and releases the memory it uses. If you do not explicitly close a cursor or result set with the close method, the JavaScript runtime engine on the server automatically closes all open cursors and result sets when the corresponding client object goes out of scope.

示例

The following example creates the rentalSet cursor, performs certain operations on it, and then closes it with the close method.

// Create a Cursor object
rentalSet = database.cursor("SELECT * FROM rentals")
// Perform operations on the cursor
cursorOperations()
//Close the cursor
err = rentalSet.close()

参看

Cursor

columnName

Returns the name of the column in the result set corresponding to the specified number.

方法源 | Resultset
实现版本 | Netscape Server 3.0

语法

columnName (n)

参数

nZero-based integer corresponding to the column in the query. The first column in the result set is 0, the second is 1, and so on.

返回

The name of the column. For Informix stored procedures, this method for the Resultset object always returns the string "Expression".

If your SELECT statement uses a wildcard (*) to select all the columns in a 表, the columnName method does not guarantee the order in which it assigns numbers to the columns. That is, suppose you have this statement:

resSet = stObj.resultSet("select * from customer"); If the customer 表 has 3 columns, ID, NAME, and CITY, you cannot tell ahead of time which of these columns corresponds to resSet.columnName(0). (Of course, you are guaranteed that successive calls to columnName have the same result.) If the order matters to you, you can instead hard-code the column names in the select statement, as in the following statement:

resSet = stObj.resultSet("select ID, NAME, CITY from customer"); With this statement, resSet.columnName(0) is ID, resSet.columnName(1) is NAME, and resSet.columnName(2) is CITY.

示例

The following example assigns the name of the first column in the customerSet cursor to the variable header:

customerSet=database.cursor(SELECT * FROM customer ORDER BY name)
header = customerSet.columnName(0)

columns

Returns the number of columns in the result set.

方法源 | Resultset
实现版本 | Netscape Server 3.0

语法

columns()

参数

 无。

返回

The number of named and unnamed columns.

示例

See Example 2 of Cursor for an example of using the columns method with the cursorColumn array.

The following example returns the number of columns in the custs cursor:

custs.columns()

next

Moves the current row to the next row in the result set.

方法源 | Resultset
实现版本 | Netscape Server 3.0

语法

next()

参数

 无。

返回

False if the current row is the last row; otherwise, true.

描述

Initially, the pointer (or current row) for a cursor or result set is positioned before the first row returned. Use the next method to move the pointer through the records in the cursor or result set. This method moves the pointer to the next row and returns true as long as there is another row available. When the cursor or result set has reached the last row, the method returns false. Note that if the cursor is empty, this method always returns false.

示例

示例 1. This example uses the next method to navigate to the last row in a cursor. The variable x is initialized to true. When the pointer is in the last row of the cursor, the next method returns false and terminates the while loop.

customerSet = database.cursor("select * from customer", true)
x = true
while (x) {
x = customerSet.next() }
示例 2. In the following example, the rentalSet cursor contains columns named videoId, rentalDate, and dueDate. The next method is called in a while loop that iterates over every row in the cursor. When the pointer is on the last row in the cursor, the next method returns false and terminates the while loop.

This example displays the three columns of the cursor in an HTML 表:

<SERVER>
// Create a Cursor object
rentalSet = database.cursor("SELECT videoId, rentalDate, returnDate
FROM rentals")
</SERVER> // Create an HTML 表
<表 BORDER>
<TR>
<TH>Video ID</TH>
<TD>Rental Date</TD>
<TD>Due Date</TD>
</TR> <SERVER>
// Iterate through each row in the cursor
while (rentalSet.next()) {
</SERVER> // Display the cursor values in the HTML 表
<TR>
<TH><SERVER>write(rentalSet.videoId)</SERVER></TH>
<TD><SERVER>write(rentalSet.rentalDate)</SERVER></TD>
<TD><SERVER>write(rentalSet.returnDate)</SERVER></TD>
</TR> // Terminate the while loop
<SERVER>
}
</SERVER> // End the 表
</表>


JavaScript语言参考手册_LiveWire 数据库服务

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

blob

 服务器端对象. Provides functionality for displaying and linking to BLOb data.

服务器端对象 |
实现版本 | LiveWire 1.0

创建源

You do not create a separate blob object. Instead, if you know that the value of a cursor property contains BLOb data, you use these methods to access that data:

blobImage | Displays BLOb data stored in a database.
blobLink | Displays a link that references BLOb data with a link.

Conversely, to store BLOb data in a database, use the blob function.

方法

blobImage

 Displays BLOb data stored in a database.

方法源 | blob
实现版本 | LiveWire 1.0

语法

cursorName.colName.blobImage (format, altText, align, widthPixels, heightPixels, borderPixels, ismap)

参数

format | The image format. This can be GIF, JPEG, or any other MIME image format. The accep表 formats are specified in the type=image section of the file $nshome\httpd-80\config\mime.types, where $nshome is the directory in which you installed your server. The client browser must also be able to display the image format.
altText | (Optional) The value of the ALT attribute of the image tag. This indicates text to display if the client browser does not display images.
align | (Optional) The value of the ALIGN attribute of the image tag. This can be "left", "right", or any other value supported by the client browser.
widthPixels | (Optional) The width of the image in pixels.
heightPixels | (Optional) The height of the image in pixels.
borderPixels | (Optional) The size of the outline border in pixels if the image is a link.
ismap | (Optional) True if the image is a clickable map. If this parameter is true, the image tag has an ISMAP attribute; otherwise it does not.

返回

An HTML IMG tag for the specified image type.

描述

Use blobImage to create an HTML image tag for a graphic image in a standard format such as GIF or JPEG.

The blobImage method fetches a BLOb from the database, creates a temporary file (in memory) of the specified format, and generates an HTML image tag that refers to the temporary file. The JavaScript runtime engine removes the temporary file after the page is generated and sent to the client.

While creating the page, the runtime engine keeps the binary data that blobImage fetches from the database in active memory, so requests that fetch a large amount of data can exceed dynamic memory on the server. Generally it is good practice to limit the number of rows retrieved at one time using blobImage to stay within the server's dynamic memory limits.

示例

示例 1. The following example extracts a row containing a small image and a name. It writes HTML containing the name and a link to the image:

cursor = connobj.cursor("SELECT NAME, THUMB FROM FISHTBL WHERE ID=2")
write(cursor.name + " ")
write(cursor.thumb.blobImage("gif"))
write("<BR>")
cursor.close()
These statements produce this HTML:

Anthia <IMG SRC="LIVEWIRE_TEMP11"><BR> 示例 2. The following example creates a cursor from the rockStarBios 表 and uses blobImage to display an image retrieved from the photos column:

cursor = database.cursor("SELECT * FROM rockStarBios
WHERE starID = 23")
while(cursor.next()) {
write(cursor.photos.blobImage("gif", "Picture", "left",
30, 30, 0,false))
}
cursor.close()
This example displays an image as if it were created by the following HTML:

<IMG SRC="livewire_temp.gif" ALT="Picture" ALIGN=LEFT
WIDTH=30 HEIGHT=30 BORDER=0> The livewire_temp.gif file in this example is the file in which the rockStarBios 表 stores the BLOb data.

blobLink

Returns a link tag that references BLOb data with a link. Creates an HTML link to the BLOb.

方法源 | blob
实现版本 | LiveWire 1.0

语法

cursorName.colName.blobLink (mimeType, linkText)

参数

mimeType | The MIME type of the binary data. This can be image/gif or any other accep表 MIME type, as specified in the Netscape server configuration file $nshome\httpd-80\config\mime.types, where $nshome is the directory in which you installed your server.
linkText | The text to display in the link. This can be any JavaScript string expression.

返回

An HTML link tag.

描述

Use blobLink if you do not want to display graphics (to reduce bandwidth requirements) or if you want to provide a link to an audio clip or other multimedia content not viewable inline.

The blobLink method fetches BLOb data from the database, creates a temporary file in memory, and generates a hypertext link to the temporary file. The JavaScript runtime engine on the server removes the temporary files that blobLink creates after the user clicks the link or sixty seconds after the request has been processed.

The runtime engine keeps the binary data that blobLink fetches from the database in active memory, so requests that fetch a large amount of data can exceed dynamic memory on the server. Generally it is good practice to limit the number of rows retrieved at one time using blobLink to stay within the server's dynamic memory limits.

示例

示例 1. The following statements extract a row containing a large image and a name. It writes HTML containing the name and a link to the image:

cursor = connobj.cursor("SELECT NAME, PICTURE FROM FISHTBL WHERE ID=2")
write(cursor.name + " ")
write(cursor.picture.blobLink("image/gif", "Link" + cursor.id))
write("<BR>")
cursor.close()
These statements produce this HTML:

Anthia <A HREF="LIVEWIRE_TEMP2">Link2</A><BR> 示例 2. The following example creates a cursor from the rockStarBios 表 and uses blobLink to create links to images retrieved from the photos column:

write("Click a link to display an image:<P>")
cursor = database.cursor("select * from rockStarBios")
while(cursor.next()) {
write(cursor.photos.blobLink("image/gif", "Image " + cursor.id))
write("<BR>")
}
cursor.close()
This example generates the following HTML:

Click a link to display an image:<P>
<A HREF="LIVEWIRE_TEMP1">Image 1</A><BR>
<A HREF="LIVEWIRE_TEMP2">Image 2</A><BR>
<A HREF="LIVEWIRE_TEMP3">Image 3</A><BR>
<A HREF="LIVEWIRE_TEMP4">Image 4</A><BR>
The LIVEWIRE_TEMP files in this example are temporary files created in memory by the blobLink method.

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


JavaScript语言参考手册_此参考中包含的内容

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

此参考中包含的内容

This reference is organized around the 函数ality of the JavaScript language. Sometimes you already know the name of an object or method, but don't know precisely where to look for it. This chapter contains tables of links to aid in this situation.

表 1, "Operators," is a list of all JavaScript operators, grouped by type of operator.

表 2, "Statements," is an alphabetical list of all JavaScript statements.

表 3, "Objects with their methods and properties," is an alphabetical list of all of JavaScript's predefined classes and objects. The predefined methods and properties for each object are listed.

表 4, "Methods," is an alphabetical list of all predefined methods, regardless of the object to which they belong. The second column indicates the object with which the method is associated. There are separate entries for methods of the same name used in different objects. Each method name links to the method in the indicated object.

Similarly, 表 5, "Properties," is an alphabetical list of all predefined properties, regardless of the object to which they belong. The second column indicates the object with which the property is associated.

表 6, "Global 函数s," is an alphabetical list of JavaScript's global 函数s. These are 函数s which aren't associated with any object.

表 7, "Event handlers," is an alphabetical list of all JavaScript event handlers.

Key to the versions
If there is an entry in both the Client Version and the Server Version columns for a single construct, that construct is part of the core language. Otherwise, it is defined only for the client or for the server, as indicated.

The version number indicates the versions of Netscape Navigator (Nav), LiveWire (LW), or the Netscape servers (Svr), such as Enterprise Server and FastTrack Server), for which the construct is defined.

  • A plus sign after a version number (as in Nav 3+) indicates that the construct is defined for that version and all later versions (In the case of server constructs, LW 1+ indicates the construct was defined for LiveWire 1.0 and continues to be defined in Netscape 3.x servers.)

  • If there is no plus sign (Nav 3) or there is a range (Nav 2-3), the construct was only defined for the named releases.

  • A construct that has existed for more than one release may have had changes between releases. For this information, see the entry for the construct.

表 1 Operators
Operator Category | Operator | Client version | Server version
Arithmetic Operators | + | Nav 2 | LW 1
 | ++ | Nav 2 | LW 1
 | - | Nav 2 | LW 1
 | -- | Nav 2 | LW 1
 | * | Nav 2 | LW 1
 | / | Nav 2 | LW 1
 | % | Nav 2 | LW 1
String Operators | + | Nav 2 | LW 1
 | += | Nav 2 | LW 1
Logical Operators | && | Nav 2 | LW 1
 | || | Nav 2 | LW 1
 | ! | Nav 2 | LW 1
Bitwise Operators | & | Nav 2 | LW 1
 | ^ | Nav 2 | LW 1
 | | | Nav 2 | LW 1
 | ~ | Nav 2 | LW 1
 | << | Nav 2 | LW 1
 | >> | Nav 2 | LW 1
 | >>> | Nav 2 | LW 1
Assignment Operators | = | Nav 2 | LW 1
 | += | Nav 2 | LW 1
 | -= | Nav 2 | LW 1
 | *= | Nav 2 | LW 1
 | /= | Nav 2 | LW 1
 | %= | Nav 2 | LW 1
 | &= | Nav 2 | LW 1
 | ^= | Nav 2 | LW 1
 | |= | Nav 2 | LW 1
 | <<= | Nav 2 | LW 1
 | >>= | Nav 2 | LW 1
 | >>>= | Nav 2 | LW 1
Comparison Operators | == | Nav 2 | LW 1
 | != | Nav 2 | LW 1
 | > | Nav 2 | LW 1
 | >= | Nav 2 | LW 1
 | < | Nav 2 | LW 1
 | <= | Nav 2 | LW 1
Special Operators | ?: | Nav 2 | LW 1
 | , | Nav 2 | LW 1
 | delete | Nav 2 | LW 1
 | new | Nav 2 | LW 1
 | this | Nav 2 | LW 1
 | typeof | Nav 3 | LW 1
 | void | Nav 3 | LW 1

表 2 Statements
Statement | Client version | Server version
break | Nav 2+ | LW 1+
comment | Nav 2+ | LW 1+
continue | Nav 2+ | LW 1+
delete | Nav 4 | Svr 3
do...while | Nav 4 | Svr 3
export | Nav 4 | Svr 3
for | Nav 2+ | LW 1+
for...in | Nav 2+ | LW 1+
函数 | Nav 2+ | LW 1+
if...else | Nav 2+ | LW 1+
import | Nav 4 | Svr 3
labeled | Nav 4 | Svr 3
return | Nav 2+ | LW 1+
switch | Nav 4 | Svr 3
var | Nav 2+ | LW 1+
while | Nav 2+ | LW 1+
with | Nav 2+ | LW 1+

表 3 Objects with their methods and properties
Object | Client version | Server version | Methods | Properties | Event handlers
Anchor | Nav 2+ |  |  |  |
Applet | Nav 3+ |  |  |  |
Area (see Link) | Nav 3+ |  |  |  |
Array | Nav 3+ (2 as non-object) | LW 1+ | concat join pop push reverse shift slice splice sort toString unshift | index input length prototype |
blob |  | LW 1+ | blobImage blobLink |  |
Boolean | Nav 3+ | LW 1+ | toString | prototype |
Button | Nav 2+ |  | blur click focus handleEvent | form name type value | onBlur onClick onFocus onMouseDown onMouseUp
Checkbox | Nav 2+ |  | blur click focus handleEvent | checked defaultChecked form name type value | onBlur onClick onFocus
client |  | LW 1+ | destroy expiration |  |
Connection |  | Svr 3 | beginTransaction commitTransaction connected cursor execute majorErrorCode majorErrorMessage minorErrorCode minorErrorMessage release rollbackTransaction SQL表 storedProc toString | prototype |
Cursor |  | LW 1+ | close columnName columns deleteRow insertRow next updateRow | cursorColumn prototype |
database |  | LW 1+ | beginTransaction commitTransaction connect connected cursor disconnect execute majorErrorCode majorErrorMessage minorErrorCode minorErrorMessage rollbackTransaction SQL表 storedProc storedProcArgs toString | prototype |
Date | Nav 2+ | LW 1+ | getDate getDay getHours getMinutes getMonth getSeconds getTime getTimezoneOffset getYear parse setDate setHours setMinutes setMonth setSeconds setTime setYear toGMTString toLocaleString UTC | prototype |
DbPool |  | Svr 3 | DbPool connect connected connection disconnect majorErrorCode majorErrorMessage minorErrorCode minorErrorMessage storedProcArgs toString |  |
document | Nav 2+ |  | captureEvents close getSelection handleEvent open releaseEvents routeEvent write writeln | alinkColor anchors applets bgColor cookie domain embeds fgColor formName forms images lastModified layers linkColor links plugins referrer title URL vlinkColor | onClick onDblClick onKeyDown onKeyPress onKeyUp onMouseDown onMouseUp
event | Nav 4 |  |  | data height layerX layerY modifiers pageX pageY screenX screenY target type which width |
File |  | LW 1+ | byteToString clearError close eof error exists flush getLength getPosition open read readByte readln setPosition stringToByte write writeByte writeln | prototype |
FileUpload | Nav 2+ |  | blur focus handleEvent select | form name type value | onBlur onChange onFocus
Form | Nav 2+ |  | handleEvent reset submit | action elements encoding length 方法 name target | onReset onSubmit
Frame (see Window) | Nav 2+ |  |  |  |
函数 | Nav 3+ | LW 1+ | toString | arguments arity caller prototype |
Hidden | Nav 2+ |  |  | form name type value |
History | Nav 2+ |  | back forward go | current length next previous |
Image | Nav 3+ |  | handleEvent | border complete height hspace lowsrc name prototype src vspace width | onAbort onError onKeyDown onKeyPress onKeyUp onLoad
Layer | Nav 4 |  | captureEvents handleEvent load moveAbove moveBelow moveBy moveTo moveToAbsolute releaseEvents resizeBy resizeTo routeEvent | above background bgColor below clip.bottom clip.height clip.left clip.right clip.top clip.width document left name pageX pageY parentLayer siblingAbove siblingBelow src top visibility zIndex | onBlur onFocus onLoad onMouseOut onMouseOver
Link | Nav 2+ |  | handleEvent | hash host hostname href pathname port protocol search target text | onClick onDblClick onKeyDown onKeyPress onKeyUp onMouseDown onMouseOut onMouseUp onMouseOver
Location | Nav 2+ |  | reload replace | hash host hostname href pathname port protocol search |
Lock |  | Svr 3 | isValid lock unlock |  |
Math | Nav 2+ | LW 1+ | abs acos asin atan atan2 ceil cos exp floor log max min pow random round sin sqrt tan | E LN10 LN2 LOG10E LOG2E PI SQRT1_2 SQRT2 |
MimeType | Nav 3+ |  |  | description enabledPlugin suffixes type |
navigator | Nav 2+ |  | javaEnabled plugins.refresh preference taintEnabled | appCodeName appName appVersion language mimeTypes platform plugins userAgent |
Number | Nav 3+ | LW 1+ |  | MAX_VALUE MIN_VALUE NaN NEGATIVE_INFINITY POSITIVE_INFINITY prototype |
Object | Nav 2+ | LW 1+ | eval toString unwatch valueOf watch | constructor prototype |
Option | Nav 2+ |  |  | defaultSelected selected text value |
Password | Nav 2+ |  | blur focus handleEvent select | defaultValue form name type value | onBlur onFocus
Plugin | Nav 3+ |  |  | description filename length name |
project |  | LW 1+ | lock unlock |  |
Radio | Nav 2+ |  | blur click focus handleEvent | checked defaultChecked form name type value | onBlur onClick onFocus
RegExp | Nav 4 | Svr 3 | compile exec test | $1, ..., $9 global ignoreCase input ($_) lastIndex lastMatch ($&) lastParen ($+) leftContext ($`) multiline ($*) rightContext ($') source |
request |  | LW 1+ |  | agent imageX imageY inputName ip 方法 protocol |
Reset | Nav 2+ |  | blur click focus handleEvent | form name type value | onBlur onClick onFocus
Resultset |  | Svr 3 | close columnName columns next | prototype |
screen | Nav 4 |  |  | availHeight availWidth colorDepth height pixelDepth width |
Select | Nav 2+ |  | blur focus handleEvent | form length name options selectedIndex type | onBlur onChange onFocus
SendMail |  | Svr 3 | errorCode errorMessage send | Bcc Body Cc Errorsto From Organization Replyto Smtpserver Subject To |
server |  | LW 1+ | lock unlock | host hostname port protocol |
Stproc |  | Svr 3 | close outParamCount outParameters resultSet returnValue | prototype |
String | Nav 2+ | LW 1+ | anchor big blink bold charAt charCodeAt concat fixed fontcolor fontsize fromCharCode indexOf italics lastIndexOf link match replace search slice small split strike sub substr substring sup toLowerCase toUpperCase | length prototype |
Submit | Nav 2+ |  | blur click focus handleEvent | form name type value | onBlur onClick onFocus
Text | Nav 2+ |  | blur focus handleEvent select | defaultValue form name type value | onBlur onChange onFocus onSelect
Textarea | Nav 2+ |  | blur focus handleEvent select | defaultValue form name type value | onBlur onChange onFocus onKeyDown onKeyPress onKeyUp onSelect
Window | Nav 2+ |  | alert back blur captureEvents clearInterval clearTimeout close confirm disableExternalCapture enableExternalCapture find focus forward handleEvent home moveBy moveTo open print prompt releaseEvents resizeBy resizeTo routeEvent scroll scrollBy scrollTo setInterval setTimeout stop | closed defaultStatus document frames history innerHeight innerWidth length location locationbar menubar name opener outerHeight outerWidth pageXOffset pageYOffset parent personalbar scrollbars self status statusbar toolbar top window | onBlur onDragDrop onError onFocus onLoad onMove onResize onUnload

表 4 Methods
Method | Of 对象 | Client version | Server Version
abs | Math | Nav 2+ | LW 1+
acos | Math | Nav 2+ | LW 1+
alert | Window | Nav 2+ |
anchor | String | Nav 2+ | LW 1+
asin | Math | Nav 2+ | LW 1+
atan | Math | Nav 2+ | LW 1+
atan2 | Math | Nav 2+ | LW 1+
back | History | Nav 2+ |
back | Window | Nav 4 |
beginTransaction | Connection |  | Svr 3
beginTransaction | database |  | LW 1+
big | String | Nav 2+ | LW 1+
blink | String | Nav 2+ | LW 1+
blobImage | blob |  | LW 1+
blobLink | blob |  | LW 1+
blur | Button | Nav 2+ |
blur | Checkbox | Nav 2+ |
blur | FileUpload | Nav 2+ |
blur | Password | Nav 2+ |
blur | Radio | Nav 2+ |
blur | Reset | Nav 2+ |
blur | Select | Nav 2+ |
blur | Submit | Nav 2+ |
blur | Text | Nav 2+ |
blur | Textarea | Nav 2+ |
blur | Window | Nav 3+ |
bold | String | Nav 2+ | LW 1+
byteToString | File |  | LW 1+
captureEvents | document | Nav 4 |
captureEvents | Layer | Nav 4 |
captureEvents | Window | Nav 4 |
ceil | Math | Nav 2+ | LW 1+
charAt | String | Nav 2+ | LW 1+
charCodeAt | String | Nav 4 | Svr 3
clearError | File |  | LW 1+
clearInterval | Window | Nav 4 |
clearTimeout | Window | Nav 2+ |
click | Button | Nav 2+ |
click | Checkbox | Nav 2+ |
click | Radio | Nav 2+ |
click | Reset | Nav 2+ |
click | Submit | Nav 2+ |
close | Cursor |  | LW 1+
close | document | Nav 2+ |
close | File |  | LW 1+
close | Resultset |  | Svr 3
close | Stproc |  | Svr 3
close | Window | Nav 2+ |
columnName | Cursor |  | LW 1+
columnName | Resultset |  | Svr 3
columns | Cursor |  | LW 1+
columns | Resultset |  | Svr 3
commitTransaction | Connection |  | Svr 3
commitTransaction | database |  | LW 1+
compile | RegExp | Nav 4 | Svr 3
concat | Array | Nav 4 | Svr 3
concat | String | Nav 4 | Svr 3
confirm | Window | Nav 2+ |
connect | database |  | LW 1+
connect | DbPool |  | Svr 3
connected | Connection |  | Svr 3
connected | database |  | LW 1+
connected | DbPool |  | Svr 3
connection | DbPool |  | Svr 3
cos | Math | Nav 2+ | LW 1+
cursor | Connection |  | Svr 3
cursor | database |  | LW 1+
DbPool | DbPool |  | Svr 3
deleteRow | Cursor |  | LW 1+
destroy | client |  | LW 1+
disableExternalCapture | Window | Nav 4 |
disconnect | database |  | LW 1+
disconnect | DbPool |  | Svr 3
enableExternalCapture | Window | Nav 4 |
eof | File |  | LW 1+
error | File |  | LW 1+
errorCode | SendMail |  | Svr 3
errorMessage | SendMail |  | Svr 3
eval | Object | Nav 3 | LW 1+
exec | RegExp | Nav 4 | Svr 3
execute | Connection |  | Svr 3
execute | database |  | LW 1+
exists | File |  | LW 1+
exp | Math | Nav 2+ | LW 1+
expiration | client |  | LW 1+
find | Window | Nav 4 |
fixed | String | Nav 2+ | LW 1+
floor | Math | Nav 2+ | LW 1+
flush | File |  | LW 1+
focus | Button | Nav 2+ |
focus | Checkbox | Nav 2+ |
focus | FileUpload | Nav 2+ |
focus | Password | Nav 2+ |
focus | Radio | Nav 2+ |
focus | Reset | Nav 2+ |
focus | Select | Nav 2+ |
focus | Submit | Nav 2+ |
focus | Text | Nav 2+ |
focus | Textarea | Nav 2+ |
focus | Window | Nav 3+ |
fontcolor | String | Nav 2+ | LW 1+
fontsize | String | Nav 2+ | LW 1+
forward | History | Nav 2+ |
forward | Window | Nav 4 |
fromCharCode | String | Nav 4 | Svr 3
getDate | Date | Nav 2+ | LW 1+
getDay | Date | Nav 2+ | LW 1+
getHours | Date | Nav 2+ | LW 1+
getLength | File |  | LW 1+
getMinutes | Date | Nav 2+ | LW 1+
getMonth | Date | Nav 2+ | LW 1+
getPosition | File |  | LW 1+
getSeconds | Date | Nav 2+ | LW 1+
getSelection | document | Nav 4 |
getTime | Date | Nav 2+ | LW 1+
getTimezoneOffset | Date | Nav 2+ | LW 1+
getYear | Date | Nav 2+ | LW 1+
go | History | Nav 2+ |
handleEvent | Button | Nav 4 |
handleEvent | Checkbox | Nav 4 |
handleEvent | document | Nav 4 |
handleEvent | FileUpload | Nav 4 |
handleEvent | Form | Nav 4 |
handleEvent | Image | Nav 4 |
handleEvent | Layer | Nav 4 |
handleEvent | Link | Nav 4 |
handleEvent | Password | Nav 4 |
handleEvent | Radio | Nav 4 |
handleEvent | Reset | Nav 4 |
handleEvent | Select | Nav 4 |
handleEvent | Submit | Nav 4 |
handleEvent | Text | Nav 4 |
handleEvent | Textarea | Nav 4 |
handleEvent | Window | Nav 4 |
home | Window | Nav 4 |
indexOf | String | Nav 2+ | LW 1+
insertRow | Cursor |  | LW 1+
isValid | Lock |  | Svr 3
italics | String | Nav 2+ | LW 1+
javaEnabled | navigator | Nav 3+ |
join | Array | Nav 3+ | LW 1+
lastIndexOf | String | Nav 2+ | LW 1+
link | String | Nav 2+ | LW 1+
load | Layer | Nav 4 |
lock | Lock |  | Svr 3
lock | project |  | LW 1+
lock | server |  | LW 1+
log | Math | Nav 2+ | LW 1+
majorErrorCode | Connection |  | Svr 3
majorErrorCode | database |  | LW 1+
majorErrorCode | DbPool |  | Svr 3
majorErrorMessage | Connection |  | Svr 3
majorErrorMessage | database |  | LW 1+
majorErrorMessage | DbPool |  | Svr 3
match | String | Nav 4 | Svr 3
max | Math | Nav 2+ | LW 1+
min | Math | Nav 2+ | LW 1+
minorErrorCode | Connection |  | Svr 3
minorErrorCode | database |  | LW 1+
minorErrorCode | DbPool |  | Svr 3
minorErrorMessage | Connection |  | Svr 3
minorErrorMessage | database |  | LW 1+
minorErrorMessage | DbPool |  | Svr 3
moveAbove | Layer | Nav 4 |
moveBelow | Layer | Nav 4 |
moveBy | Layer | Nav 4 |
moveBy | Window | Nav 4 |
moveTo | Layer | Nav 4 |
moveTo | Window | Nav 4 |
moveToAbsolute | Layer | Nav 4 |
next | Cursor |  | LW 1+
next | Resultset |  | Svr 3
open | document | Nav 2+ |
open | File |  | LW 1+
open | Window | Nav 2+ |
outParamCount | Stproc |  | Svr 3
outParameters | Stproc |  | Svr 3
parse | Date | Nav 2+ | LW 1+
plugins.refresh | navigator | Nav 3+ |
pop | Array | Nav 4 | Svr 3
pow | Math | Nav 2+ | LW 1+
preference | navigator | Nav 4 |
print | Window | Nav 4 |
prompt | Window | Nav 2+ |
push | Array | Nav 4 | Svr 3
random | Math | Nav 2+ | LW 1+
read | File |  | LW 1+
readByte | File |  | LW 1+
readln | File |  | LW 1+
refresh | navigator.plugins | Nav 3+ |
release | Connection |  | Svr 3
releaseEvents | document | Nav 4 |
releaseEvents | Layer | Nav 4 |
releaseEvents | Window | Nav 4 |
reload | Location | Nav 3+ |
replace | Location | Nav 3+ |
replace | String | Nav 4 | Svr 3
reset | Form | Nav 3+ |
resizeBy | Layer | Nav 4 |
resizeBy | Window | Nav 4 |
resizeTo | Layer | Nav 4 |
resizeTo | Window | Nav 4 |
resultSet | Stproc |  | Svr 3
returnValue | Stproc |  | Svr 3
reverse | Array | Nav 3+ | LW 1+
rollbackTransaction | Connection |  | Svr 3
rollbackTransaction | database |  | LW 1+
round | Math | Nav 2+ | LW 1+
routeEvent | document | Nav 4 |
routeEvent | Layer | Nav 4 |
routeEvent | Window | Nav 4 |
scroll | Window | Nav 2-3 |
scrollBy | Window | Nav 4 |
scrollTo | Window | Nav 4 |
search | String | Nav 4 | Svr 3
select | FileUpload | Nav 2+ |
select | Password | Nav 2+ |
select | Text | Nav 2+ |
select | Textarea | Nav 2+ |
send | SendMail |  | Svr 3
setDate | Date | Nav 2+ | LW 1+
setHours | Date | Nav 2+ | LW 1+
setInterval | Window | Nav 4 |
setMinutes | Date | Nav 2+ | LW 1+
setMonth | Date | Nav 2+ | LW 1+
setPosition | File |  | LW 1+
setSeconds | Date | Nav 2+ | LW 1+
setTime | Date | Nav 2+ | LW 1+
setTimeout | Window | Nav 2+ |
setYear | Date | Nav 2+ | LW 1+
shift | Array | Nav 4 | Svr 3
sin | Math | Nav 2+ | LW 1+
slice | Array | Nav 4 | Svr 3
slice | String | Nav 4 | Svr 3
small | String | Nav 2+ | LW 1+
sort | Array | Nav 3+ | LW 1+
splice | Array | Nav 4 | Svr 3
split | String | Nav 3+ | LW 1+
SQL表 | Connection |  | Svr 3
SQL表 | database |  | LW 1+
sqrt | Math | Nav 2+ | LW 1+
stop | Window | Nav 4 |
storedProc | Connection |  | Svr 3
storedProc | database |  | Svr 3
storedProcArgs | database |  | Svr 3
storedProcArgs | DbPool |  | Svr 3
strike | String | Nav 2+ | LW 1+
stringToByte | File |  | LW 1+
sub | String | Nav 2+ | LW 1+
submit | Form | Nav 2+ |
substr | String | Nav 4 | Svr 3
substring | String | Nav 2+ | LW 1+
sup | String | Nav 2+ | LW 1+
taintEnabled | navigator | Nav 3 | LW 1
tan | Math | Nav 2+ | LW 1+
test | RegExp | Nav 4 | Svr 3
toGMTString | Date | Nav 2+ | LW 1+
toLocaleString | Date | Nav 2+ | LW 1+
toLowerCase | String | Nav 2+ | LW 1+
toString | Array | Nav 3+ | LW 1+
toString | Boolean | Nav 3+ | LW 1+
toString | Connection |  | Svr 3
toString | database |  | LW 1+
toString | DbPool |  | Svr 3
toString | Number | Nav 3+ | LW 1+
toString | Object | Nav 2+ | LW 1+
toUpperCase | String | Nav 2+ | LW 1+
unlock | Lock |  | Svr 3
unlock | project |  | LW 1+
unlock | server |  | LW 1+
unshift | Array | Nav 4 | Svr 3
unwatch | Object | Nav 4 | Svr 3
updateRow | Cursor |  | LW 1+
UTC | Date | Nav 2+ | LW 1+
valueOf | Object | Nav 3+ | LW 1+
watch | Object | Nav 4 | Svr 3
write | document | Nav 2+ |
write | File |  | LW 1+
writeByte | File |  | LW 1+
writeln | document | Nav 2+ |
writeln | File |  | LW 1+

表 5 Properties
Property | Of 对象 | Client version | Server version
$1, ..., $9 | RegExp | Nav 4 | Svr 3
$_ | RegExp | Nav 4 | Svr 3
$* | RegExp | Nav 4 | Svr 3
$& | RegExp | Nav 4 | Svr 3
$+ | RegExp | Nav 4 | Svr 3
$` | RegExp | Nav 4 | Svr 3
$' | RegExp | Nav 4 | Svr 3
above | Layer | Nav 4 |
action | Form | Nav 2+ |
agent | request |  | LW 1+
alinkColor | document | Nav 2+ |
anchors | document | Nav 2+ |
appCodeName | navigator | Nav 2+ |
applets | document | Nav 3+ |
appName | navigator | Nav 2+ |
appVersion | navigator | Nav 2+ |
arguments | 函数 | Nav 3+ | LW 1+
arity | 函数 | Nav 4 | LW 1+
background | Layer | Nav 4 |
below | Layer | Nav 4 |
bgColor | document | Nav 2+ |
bgColor | Layer | Nav 4 |
border | Image | Nav 3+ |
caller | 函数 | Nav 3+ | LW 1+
checked | Checkbox | Nav 2+ |
checked | Radio | Nav 2+ |
clip.bottom | Layer | Nav 4 |
clip.height | Layer | Nav 4 |
clip.left | Layer | Nav 4 |
clip.right | Layer | Nav 4 |
clip.top | Layer | Nav 4 |
clip.width | Layer | Nav 4 |
closed | Window | Nav 3+ |
colorDepth | screen | Nav 4 |
complete | Image | Nav 3+ |
constructor | Object | Nav 3+ | LW 1+
cookie | document | Nav 2+ |
current | History | Nav 3+ |
cursorColumn | Cursor |  | LW 1+
data | event | Nav 4 |
defaultChecked | Checkbox | Nav 2+ |
defaultChecked | Radio | Nav 2+ |
defaultStatus | Window | Nav 2+ |
defaultSelected | Option | Nav 3+ |
defaultValue | Password | Nav 2+ |
defaultValue | Text | Nav 2+ |
defaultValue | Textarea | Nav 2+ |
description | MimeType | Nav 3+ |
description | Plugin | Nav 3+ |
document | Layer | Nav 4 |
document | Window | Nav 2+ |
domain | document | Nav 3+ |
E | Math | Nav 2+ | LW 1+
elements | Form | Nav 2+ |
embeds | document | Nav 3+ |
enabledPlugin | MimeType | Nav 3+ |
encoding | Form | Nav 2+ |
fgColor | document | Nav 2+ |
filename | Plugin | Nav 3+ |
form | Button | Nav 2+ |
form | Checkbox | Nav 2+ |
form | FileUpload | Nav 2+ |
form | Hidden | Nav 2+ |
form | Password | Nav 2+ |
form | Radio | Nav 2+ |
form | Reset | Nav 2+ |
form | Select | Nav 2+ |
form | Submit | Nav 2+ |
form | Text | Nav 2+ |
form | Textarea | Nav 2+ |
formName | document | Nav 3+ |
forms | document | Nav 3+ |
frames | Window | Nav 2+ |
global | RegExp | Nav 4 | Svr 3
hash | Link | Nav 2+ |
hash | Location | Nav 2+ |
height | event | Nav 4 |
height | Image | Nav 3+ |
height | screen | Nav 4 |
history | Window | Nav 2+ |
host | Link | Nav 2+ |
host | Location | Nav 2+ |
host | server |  | LW 1+
hostname | Link | Nav 2+ |
hostname | Location | Nav 2+ |
hostname | server |  | LW 1+
href | Link | Nav 2+ |
href | Location | Nav 2+ |
hspace | Image | Nav 3+ |
ignoreCase | RegExp | Nav 4 | Svr 3
images | document | Nav 3+ |
imageX | request |  | LW 1+
imageY | request |  | LW 1+
index | Array | Nav 4 | Svr 3
input | Array | Nav 4 | Svr 3
innerHeight | Window | Nav 4 |
innerWidth | Window | Nav 4 |
input | RegExp | Nav 4 | Svr 3
inputName | request |  | LW 1+
ip | request |  | LW 1+
language | navigator | Nav 4 |
lastIndex | RegExp | Nav 4 | Svr 3
lastMatch | RegExp | Nav 4 | Svr 3
lastModified | document | Nav 2+ |
lastParen | RegExp | Nav 4 | Svr 3
layerX | event | Nav 4 |
layerY | event | Nav 4 |
layers | document | Nav 4 |
left | Layer | Nav 4 |
leftContext | RegExp | Nav 4 | Svr 3
length | Array | Nav 3+ | LW 1+
length | Form | Nav 2+ |
length | History | Nav 2+ |
length | Plugin | Nav 3+ |
length | Select | Nav 2+ |
length | String | Nav 2+ | LW 1+
length | Window | Nav 2+ |
linkColor | document | Nav 2+ |
links | document | Nav 2+ |
location | Window | Nav 2+ |
locationbar | Window | Nav 4 |
LN10 | Math | Nav 2+ | LW 1+
LN2 | Math | Nav 2+ | LW 1+
LOG10E | Math | Nav 2+ | LW 1+
LOG2E | Math | Nav 2+ | LW 1+
lowsrc | Image | Nav 3+ |
MAX_VALUE | Number | Nav 3+ | LW 1+
menubar | Window | Nav 4 |
方法 | Form | Nav 2+ |
方法 | request |  | LW 1+
mimeTypes | navigator | Nav 3+ |
modifiers | event | Nav 4 |
MIN_VALUE | Number | Nav 3+ | LW 1+
multiline | RegExp | Nav 4 | Svr 3
name | Button | Nav 2+ |
name | Checkbox | Nav 2+ |
name | FileUpload | Nav 2+ |
name | Form | Nav 2+ |
name | Hidden | Nav 2+ |
name | Image | Nav 3+ |
name | Layer | Nav 4 |
name | Password | Nav 2+ |
name | Plugin | Nav 3+ |
name | Radio | Nav 2+ |
name | Reset | Nav 2+ |
name | Select | Nav 2+ |
name | Submit | Nav 2+ |
name | Text | Nav 2+ |
name | Textarea | Nav 2+ |
name | Window | Nav 2+ |
NaN | Number | Nav 3+ | LW 1+
NEGATIVE_INFINITY | Number | Nav 3+ | LW 1+
next | History | Nav 3+ |
opener | Window | Nav 3+ |
options | Select | Nav 2+ |
outerHeight | Window | Nav 4 |
outerWidth | Window | Nav 4 |
pageX | event | Nav 4 |
pageX | Layer | Nav 4 |
pageXOffset | Window | Nav 4 |
pageY | event | Nav 4 |
pageY | Layer | Nav 4 |
pageYOffset | Window | Nav 4 |
parent | Window | Nav 2+ |
parentLayer | Layer | Nav 4 |
pathname | Link | Nav 2+ |
pathname | Location | Nav 2+ |
personalbar | Window | Nav 4 |
PI | Math | Nav 2+ | LW 1+
pixelDepth | screen | Nav 4 |
platform | navigator | Nav 4 |
plugins | document | Nav 3+ |
plugins | navigator | Nav 3+ |
port | Link | Nav 2+ |
port | Location | Nav 2+ |
port | server |  | LW 1+
POSITIVE_INFINITY | Number | Nav 3+ | LW 1+
previous | History | Nav 3+ |
protocol | Link | Nav 2+ |
protocol | Location | Nav 2+ |
protocol | request |  | LW 1+
protocol | server |  | LW 1+
prototype | Array | Nav 3+ | LW 1+
prototype | Boolean | Nav 3+ | LW 1+
prototype | Connection |  | Svr 3
prototype | Cursor | Nav 3+ | LW 1+
prototype | database |  | LW 1+
prototype | Date | Nav 3+ | LW 1+
prototype | DbPool |  | Svr 3
prototype | File |  | LW 1+
prototype | 函数 | Nav 3+ | LW 1+
prototype | Image | Nav 3+ | LW 1+
prototype | Number | Nav 3+ | LW 1+
prototype | Object | Nav 3+ | LW 1+
prototype | Resultset |  | Svr 3
prototype | SendMail |  | Svr 3
prototype | Stproc |  | Svr 3
prototype | String | Nav 3+ | LW 1+
referrer | document | Nav 2+ |
rightContext | RegExp | Nav 4 | Svr 3
screenX | event | Nav 4 |
screenY | event | Nav 4 |
scrollbars | Window | Nav 4 |
search | Link | Nav 2+ |
search | Location | Nav 2+ |
selected | Option | Nav 2+ |
selectedIndex | Select | Nav 2+ |
self | Window | Nav 2+ |
siblingAbove | Layer | Nav 4 |
siblingBelow | Layer | Nav 4 |
source | RegExp | Nav 4 | Svr 3
SQRT1_2 | Math | Nav 2+ | LW 1+
SQRT2 | Math | Nav 2+ | LW 1+
src | Image | Nav 3+ |
src | Layer | Nav 4 |
status | Window | Nav 2+ |
statusbar | Window | Nav 4 |
suffixes | MimeType | Nav 3+ |
target | event | Nav 4 |
target | Form | Nav 2+ |
target | Link | Nav 2+ |
text | Option | Nav 2+ |
text | Link | Nav 4 |
title | document | Nav 2+ |
toolbar | Window | Nav 4 |
top | Layer | Nav 4 |
top | Window | Nav 2+ |
type | Button | Nav 3+ |
type | Checkbox | Nav 3+ |
type | event | Nav 4 |
type | FileUpload | Nav 3+ |
type | Hidden | Nav 3+ |
type | Password | Nav 3+ |
type | MimeType | Nav 3+ |
type | Radio | Nav 3+ |
type | Reset | Nav 3+ |
type | Select | Nav 3+ |
type | Submit | Nav 3+ |
type | Text | Nav 3+ |
type | Textarea | Nav 3+ |
URL | document | Nav 2+ |
userAgent | navigator | Nav 2+ |
value | Button | Nav 2+ |
value | Checkbox | Nav 2+ |
value | FileUpload | Nav 2+ |
value | Hidden | Nav 2+ |
value | Option | Nav 2+ |
value | Password | Nav 2+ |
value | Radio | Nav 2+ |
value | Reset | Nav 2+ |
value | Submit | Nav 2+ |
value | Text | Nav 2+ |
value | Textarea | Nav 2+ |
visibility | Layer | Nav 4 |
vlinkColor | document | Nav 2+ |
vspace | Image | Nav 3+ |
which | event | Nav 4 |
width | event | Nav 4 |
width | Image | Nav 3+ |
width | screen | Nav 4 |
window | Window | Nav 2+ |
zIndex | Layer | Nav 4 |

表 6 Global 函数s
函数 | Client version | Server version
addClient |  | LW 1+
addResponseHeader |  | Svr 3
blob |  | LW 1+
callC |  | LW 1+
debug |  | LW 1+
deleteResponseHeader |  | Svr 3
escape | Nav 2+ | LW 1+
eval | Nav 2+ | LW 1+
flush |  | LW 1+
getOptionValue |  | LW 1+
getOptionValueCount |  | LW 1+
isNaN | Nav 3+ | LW 1+
Number | Nav 4 | Svr 3
parseFloat | Nav 3+ | LW 1+
parseInt | Nav 3+ | LW 1+
redirect |  | LW 1+
registerC函数 |  | LW 1+
ssjs_generateClientID |  | Svr 3
ssjs_getCGIVariable |  | Svr 3
ssjs_getClientID |  | Svr 3
String | Nav 4 | Svr 3
taint | Nav 3 | LW 1+
unescape | Nav 2+ | LW 1+
untaint | Nav 3 | LW 1+
write |  | LW 1+

表 7 Event handlers
Event handler | Client version | Handler for
onAbort | Nav 3+ | Image
onBlur | Nav 3+ | Button, Checkbox, FileUpload, Layer, Password, Radio, Reset, Select, Submit, Text, Textarea, Window
onChange | Nav 3+ | FileUpload, Select, Text, Textarea
onClick | Nav 3+ | Button, Checkbox, document, Link, Radio, Reset, Submit
onDblClick | Nav 4 | document, Link
onDragDrop | Nav 4 | Window
onError | Nav 3+ | Image, Window
onFocus | Nav 3+ | Button, Checkbox, FileUpload, Layer, Password, Radio, Reset, Select, Submit, Text, Textarea, Window
onKeyDown | Nav 4 | document, Image, Link, Textarea
onKeyPress | Nav 4 | document, Image, Link, Textarea
onKeyUp | Nav 4 | document, Image, Link, Textarea
onLoad | Nav 3+ | Image, Layer, Window
onMouseDown | Nav 4 | Button, document, Link
onMouseMove | Nav 4 |
onMouseOut | Nav 3+ | Layer, Link
onMouseOver | Nav 3+ | Layer, Link
onMouseUp | Nav 4 | Button, document, Link
onMove | Nav 4 | Window
onReset | Nav 3+ | Form
onResize | Nav 4 | Window
onSelect | Nav 3+ | Text, Textarea
onSubmit | Nav 3+ | Form
onUnload | Nav 3+ | Window

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


JavaScript语言参考手册_操作符

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

第二章
操作符

JavaScript 有赋值、比较、算术、位、逻辑、字符串和特殊运算符。本章描述了操作符，以及关于操作符优先级的一些信息。

表 2.1 JavaScript 所有操作符简明列表。

表 2.1 JavaScript 操作符
操作符分类 | 操作符 | 描述
算 术 操 作 符 | + | (加法) 将两个数相加。
 | ++ | (自增) 将表示数值的变量加一(可以返回新值或旧值)。
 | - | (求相反数，减法) 作为求相反数操作符时返回参数的相反数。作为二进制操作符时，将两个数相减。
 | -- | (自减) 将表示数值的变量减一(可以返回新值或旧值)。
 | * | (乘法) 将两个数相乘。
 | / | (除法) 将两个数相除。
 | % | (求余) 求两个数相除的余数。
字符串操作符 | + | (字符串加法) 连接两个字符串。
 | += | 连接两个字符串，并将结果赋给第一个字符串。
逻 辑 操 作 符 | && | (逻辑与) 如果两个操作数都是真的话则返回真。否则返回假。
 | || | (逻辑或) 如果两个操作数都是假的话则返回假。否则返回真。
 | ! | (逻辑非) 如果其单一操作数为真，则返回假。否则返回真。
位 操 作 符 | & | (按位与) 如果两个操作数对应位都是 1 的话则在该位返回 1。
 | ^ | (按位异或) 如果两个操作数对应位只有一个 1 的话则在该位返回 1。
 | | | (按位或) 如果两个操作数对应位都是 0 的话则在该位返回 0。
 | ~ | (求反) 反转操作数的每一位。
 | << | (左移) 将第一操作数的二进制形式的每一位向左移位，所移位的数目由第二操作数指定。右面的空位补零。
 | >> | (算术右移) 将第一操作数的二进制形式的每一位向右移位，所移位的数目由第二操作数指定。忽略被移出的位。
 | >>> | (逻辑右移) 将第一操作数的二进制形式的每一位向右移位，所移位的数目由第二操作数指定。忽略被移出的位，左面的空位补零。
赋 值 操 作 符 | = | 将第二操作数的值赋给第一操作数。
 | += | 将两个数相加，并将和赋给第一个数。
 | -= | 将两个数相减，并将差赋给第一个数。
 | *= | 将两个数相乘，并将积赋给第一个数。
 | /= | 将两个数相除，并将商赋给第一个数。
 | %= | 计算两个数相除的余数，并将余数赋给第一个数。
 | &= | 执行按位与，并将结果赋给第一个操作数。
 | ^= | 执行按位异或，并将结果赋给第一个操作数。
 | |= | 执行按位或，并将结果赋给第一个操作数。
 | <<= | 执行左移，并将结果赋给第一个操作数。
 | >>= | 执行算术右移，并将结果赋给第一个操作数。
 | >>>= | 执行逻辑右移，并将结果赋给第一个操作数。
比 较 操 作 符 | == | 如果操作数相等的话则返回真。
 | != | 如果操作数不相等的话则返回真。
 | > | 如果左操作数大于右操作数的话则返回真。
 | >= | 如果左操作数大于等于右操作数的话则返回真。
 | < | 如果左操作数小于右操作数的话则返回真。
 | <= | 如果左操作数小于等于右操作数的话则返回真。
特 殊 操 作 符 | ?: | 执行一个简单的“if...else”语句。
 | , | 计算两个表达式，返回第二个表达式的值。
 | delete | 允许你删除一个对象的属性或数组中指定的元素。
 | new | 允许你创建一个用户自定义对象类型或内建对象类型的实例。
 | this | 可用于引用当前对象的关键字。
 | typeof | 返回一个字符串，表明未计算的操作数的类型。
 | void | 该操作符指定了要计算一个表达式但不返回值。

赋值操作符

赋值操作符会根据其右操作数侧的值给左操作数赋值。

实现版本 Navigator 2.0

最基本的赋值操作数是等号(=)，它会将右操作数的值直接赋给左操作数。也就是说，x = y 将把 y 的值赋给 x。其它的赋值操作符都是标准操作的缩略形式，列在表 2.2 中。

表 2.2 赋值操作符
缩写操作符 | 含义
x += y | x = x + y
x -= y | x = x - y
x *= y | x = x * y
x /= y | x = x / y
x %= y | x = x % y
x <<= y | x = x << y
x >>= y | x = x >> y
x >>>= y | x = x >>> y
x &= y | x = x & y
x ^= y | x = x ^ y
x |= y | x = x | y

比较操作符

所谓比较操作符，就是会比较其两边的操作数，并根据比较结果为真或假返回逻辑值。操作数可以是数值或字符串值。如果使用字符串值的话，比较是基于标准的字典顺序。

实现版本 Navigator 2.0

相关内容列在了表 2.3 中。对于该表中的示例，我们假定 var1 被赋予了值 3，而 var2 被赋予了值 4。

表 2.3 比较操作符
操作符 | 描述 | 返回真的例子
相等(==) | 如果操作数相等的话则返回真。 | 3 == var1
不等(!=) | 如果操作数不等的话则返回真。 | var1 != 4
大于(>) | 如果左操作数大于右操作数的话则返回真。 | var2 > var1
大于或等于(>=) | 如果左操作数大于等于右操作数的话则返回真。 | var2 >= var1 var1 >= 3
小于(<) | 如果左操作数小于右操作数的话则返回真。 | var1 < var2
小于或等于(<=) | 如果左操作数小于等于右操作数的话则返回真。 | var1 <= var2 var2 <= 5

算术操作符

将给定数值(常量或变量)进行给定的计算，并返回一个数值。标准的算术操作符是加(+)、减(-)、乘(*)、除(/)四则运算。这些操作符与在其它编程语言中的作用一样。

实现版本 Navigator 2.0

% (取余)

取余操作符用法如下：

var1 % var2

取余运算符将返回第一个操作数除以第二个操作数的余数。对于上面的例子来说，将返回 var1 变量除以 var2 变量的余数。更具体的例子是，12 % 5 将返回 2。

++ (自增)

自增操作符用法如下：

var++ 或 ++var

该自增操作符将自增操作数(自己加上 1)并返回一个值。如果写在变量后面(如 x++)，将返回自增前的值。如果写在变量前面(如 ++x)，将返回自增后的值。

例如，如果 x 是 3，那么语句 y = x++ 将先把 y 置为 3 再将 x 自增为 4。相反，语句 y = ++x 将先将 x 自增为 4，再将 y 置为 4。

-- (自减)

自减操作符用法如下：

var-- 或 --var

该自增操作符将自减操作数(自己减去 1)并返回一个值。如果写在变量后面(如 x--)，将返回自减前的值。如果写在变量前面(如 --x)，将返回自减后的值。

例如，如果 x 是 3，那么语句 y = x-- 将先把 y 置为 3 再将 x 自减为 2。相反，语句 y = --x 将先将 x 自减为 2，再将 y 置为 2。

- (求相反数)

求相反数操作数将取得操作数的相反数。例如，y = -x 将把 x 相反数的值赋给 y；也就是说，如果 x 是 3 的话，y 就会获得 -3 而 x 还是 3。

位操作符

执行位操作时，操作符会将操作数看作一串二进制位(1和0)，而不是十进制、十六进制或八进制数字。例如，十进制的 9 就是二进制的 1001。位操作符在执行的时候会以二进制形式进行操作，但返回的值仍是标准的 JavaScript 数值。

表 2.4 JavaScript 位操作符总览

表 2.4 位操作符
操作符 | 用法 | 描述
按位与 | a & b | 如果两个操作数对应位都是 1 的话则在该位返回 1。
按位或 | a | b | 如果两个操作数对应位都是 0 的话则在该位返回 0。
按位异或 | a ^ b | 如果两个操作数对应位只有一个 1 的话则在该位返回 1。
求反 | ~ a | 反转操作数的每一位。
左移 | a << b | 将 a 的二进制形式左移 b 位。右面的空位补零。
算术右移 | a >> b | 将 a 的二进制形式右移 b 位。忽略被移出的位。
逻辑右移 | a >>> b | 将 a 的二进制形式右移 b 位。忽略被移出的位，左侧补入 0。

位逻辑操作符

实现版本 Navigator 2.0

从原理上讲，位逻辑操作符的工作流程是这样的：

  • 将操作数转换为 32 位的整型数值并用二进制表示。

  • 第一操作数的每一位与第二操作数的对应位配对：第一位对第一位，第二位对第二位，以此类推。

  • 对每一对位应用操作符，最终结果按位组合起来。
例如，9 的二进制表示为 1001，15 的二进制表示为 1111。所以如果对这两个数应用位逻辑操作符，结果应该像下面这样：

  • 15 & 9 结果为 9 (1111 & 1001 = 1001)

  • 15 | 9 为 15 (1111 | 1001 = 1111)

  • 15 ^ 9 为 6 (1111 ^ 1001 = 0110)

移位操作符

实现版本 Navigator 2.0

移位操作符需要两个操作数：第一个是要进行移位的数值，第二个指定要对第一个数移位的数目。移位的方向由使用的操作符决定。

移位操作符将把两个操作符转换为 32 位整型数值，并返回与左操作数类型相同的结果。

<< (左移)

该操作符将把第一个操作数向左移若干位。移出的位将被忽略。右侧空位补零。

例如，9<<2 结果为 36，因为 1001 向左移两位变成 100100，这是 36。

>> (算术右移)

该操作符将把第一个操作数享有移若干位。移出的位将被忽略。左侧的空位补上与原来最左面位相同的值。

例如，9>>2 结果为 2，因为 1001 右移两位变成 10，这是 2。反之，-9>>2 结果为 -3，因为要考虑到符号位。

>>> (逻辑右移)

该操作符将把第一个操作数享有移若干位。移出的位将被忽略。左侧的空位补零。

例如，19>>>2 结果为 4，因为 10011 右移两位变成 100，这是 4。对于非负数，算术右移和逻辑右移结果相同。

逻辑操作符

逻辑操作符用 Boolean 值(布尔逻辑值)作为操作数，并返回 Boolean 值。

实现版本 Navigator 2.0

表 2.5 描述的很清楚。

表 2.5 逻辑操作符
操作符 | 用法 | 描述
与(&&) | expr1 && expr2 | 如果 expr1 为假则返回之，否则返回 expr2。
或(||) | expr1 || expr2 | 如果 expr1 为真则返回之，否则返回 expr2。
非(!) | !expr | 如果 expr 为真则返回假，否则返回真。

示例

考虑下面的脚本：

  <script language="JavaScript1.2">"
v1 = "猫";
v2 = "狗";
v3 = false;
document.writeln("t && t 返回 "  + (v1 && v2));
document.writeln("f && t 返回 " + (v3 && v1));
document.writeln("t && f 返回 " + (v1 && v3));
document.writeln("f && f 返回 " + (v3 && (3 == 4)));
  document.writeln("t || t 返回 " + (v1 || v2));
document.writeln("f || t 返回 " + (v3 || v1));
document.writeln("t || f 返回 " + (v1 || v3));
document.writeln("f || f 返回 " + (v3 || (3 == 4)));
document.writeln("!t 返回 " + (!v1));
document.writeln("!f 返回 " + (!v3));
</script>

该脚本将显示下列内容：

t && t 返回 狗
f && t 返回 false
t && f 返回 false
f && f 返回 false
t || t 返回 猫
f || t 返回 猫
t || f 返回 猫
f || f 返回 false
!t 返回 false
!f 返回 true

简化计算

由于逻辑表达式是从左到右计算的，计算机自然不会傻到真的将全部表达式都计算一遍，它会试着偷偷懒，想办法按照下面的规则“简化”计算：

  • false && 任何值 都会被简化为 false。

  • true || 任何值 都会被简化计算为 true。
逻辑运算的简化原则是保证逻辑运算本身总是正确的。请注意，如果使用了简化规则，那么被简化掉的表达式就不会进行计算，所以也就不会产生它应该起的作用。

字符串操作符

除了比较操作符，可应用于字符串值的操作符还有连接操作符(+)，它会将两个字符串连接在一起，并返回连接的结果。例如，“my ” +“string”将返回字符串“my string”。

实现版本 Navigator 2.0

组合赋值操作符 += 也可用于连接字符串。例如，如果变量 mystring 的值为“alpha”，表达式 mystring += "bet" 将计算出“alphabet”并将其赋给 mystring。

特殊操作符

?: (条件操作符)

 条件操作符是 JavaScript 所有操作符之中唯一需要三个操作数的。该操作符通常用于取代简单的 if 语句。

实现版本 Navigator 2.0

语法

condition ? expr1 : expr2

参数

condition | 计算结果为 true 或 false 的表达式
expr1, expr2 | 任意类型值的表达式。

描述

如果 condition 为真的话，该操作符将返回 expr1 的值；否则返回 expr2 的值。例如，要根据 isMember 变量的值显示不同的信息，可以使用此语句：

document.write ("收费为 " + (isMember ? "$2.00" : "$10.00"))

, (逗号操作符)

逗号操作符非常简单。它会依次计算两个操作数并返回第二个操作数的值。

实现版本 Navigator 2.0

语法

expr1, expr2

参数

expr1, expr2 任意表达式

描述

你可以在你想要在只能填入一个表达式的地方写入多个表达式时使用逗号操作符。该操作符最常见的用途是在 for 语句中使用多个变量作为循环变量。

例如，如果 a 是一个 10x10 的二维数组，下面的代码将使用逗号操作符一次自增两个变量。结果是打印出该数组副对角线上的元素：

for (var i=0, j=10; i <= 10; i++, j--)
document.writeln("a["+i+","+j+"]= " + a[i,j])

delete

删除一个对象的属性或者数组中特定位置的元素。

实现版本 Navigator 2.0

语法

delete objectName.property
delete objectName[index]
delete property

参数

objectName | 对象的名称。
属性 | 已有的属性。
index | 一个整型数值，表明了要删除的元素在数组处的位置。

描述

第三种格式只在 with 语句中合法。

如果删除成功，delete 操作符将把属性或元素设为 undefined(未定义)。delete 总是返回 undefined。

new

该操作符用于创建用户自定义对象类型或者拥有构造函数的内建对象类型的实例。

实现版本 Navigator 2.0

语法

objectName = new objectType (param1 [,param2] ...[,paramN])

参数

objectName | 新对象实例的名称。
objectType | 对象类型。它必须是一个定义对象类型的函数。
param1...paramN | 对象的属性值。这些属性是 objectType 函数的参数。

描述

创建一个用户自定义对象需要两个步骤：

  1. 写一个函数定义一种对象类型。

  2. 用 new 创建一个该对象的实例。
要定义一个对象类型，需要为该对象创建一个指定名称、属性和方法的函数。一个对象的属性可以是其它类型的对象。请参看下面的例子。

你总可以向已经定义的对象中添加属性。例如，car1.color = "black" 将给 car1 添加一个叫 color 的属性，并给其赋值“black”。不过这对其它任何对象并没有什么作用。要给同一类型的所有对象都添加一个新的属性，你必须向 car 对象类型的定义中添加属性。

你可以使用 Function.prototype 属性向先前定义的对象类型中添加属性。 这将定义一个被所有由该函数创建的对象共享的属性，而不只是一个对象类型实例才有。下面的代码将为所有 car 类型的对象添加一个 color 属性，然后将对象 car1 的 color 属性赋值。更多信息，请参看 prototype。

Car.prototype.color=null
car1.color="black"

示例

示例 1：对象类型和对象实例。假设你想要创建一个汽车使用的对象类型。你想要这种对象类型叫做 car，有属性 make, model, 和 year。要完成这么多事情，你需要编写如下的函数：

function car(make, model, year) {
this.make = make
this.model = model
this.year = year
}
现在你就可以用下面的方法创建一个叫做 mycar 的对象了：

mycar = new car("Eagle", "Talon TSi", 1993)

该语句创建了 mycar 并将其属性赋了指定的值。也就是说，mycar.make 的值是字符串“Eagle”，mycar.year 是整型数 1993，等等。

使用 new 你可以创建任意多个 car 对象。如，

kenscar = new car("Nissan", "300ZX", 1992) 示例 2: 对象属性就是另外一个对象。假设你按照下面代码定义了一个叫做 person 的对象类型：

function person(name, age, sex) {
this.name = name
this.age = age
this.sex = sex
}
然后创建了两个新的 person 实例：

rand = new person("Rand McNally", 33, "M")
ken = new person("Ken Jones", 39, "M")
现在你可以重写 car 的定义，以便包含一个 person 对象作为 owner 属性表明车主：

function car(make, model, year, owner) {
this.make = make;
this.model = model;
this.year = year;
this.owner = owner;
}
要创建一个新对象的实例，你可以使用下面的代码：

car1 = new car("Eagle", "Talon TSi", 1993, rand);
car2 = new car("Nissan", "300ZX", 1992, ken)

请注意，我们在创建对象的时候并没有给出一个常量字符串或者一个整型值，而是传递了对象 kand 和 ken 作为 owner 的参数。要找出 car2 车主的名字的方法是：

car2.owner.name

this

该关键字用于引用当前对象，通常情况下，方法中的 this 指调用它的对象。

实现版本 Navigator 2.0

语法

this[.propertyName]

示例

 假定有一个叫做 validate 的函数可以校验对象的 value 属性，如果给出对象值的上下限的话：

function validate(obj, lowval, hival) {
if ((obj.value < lowval) || (obj.value > hival))
alert("无效数据e!")
}

你可以在每个窗体元素的 onChange 事件句柄中调用 validate，只用下面的格式传递 this 作为参数就行了：

<B>请输入 18 到 99 之间的数值：</B>
<INPUT TYPE = "text" NAME = "age" SIZE = 3
onChange="validate(this, 18, 99)">

typeof

typeof 操作符用法格式如下：

1. typeof operand
2. typeof (operand)

typeof 操作符将返回一个字符串，表明未计算的 operand 操作数是什么类型的。operand 是一个要返回类型的字符串变量、关键字或者对象。圆括号可选。

实现版本 Navigator 3.0

假设你定义了下面的变量：

var myFun = new Function("5+2")
var shape="round"
var size=1
var today=new Date()

typeof 操作符将返回下面的值：

typeof myFun is object
typeof shape is string
typeof size is number
typeof today is object
typeof dontExist is undefined

对于关键字 true 和 null，typeof 操作符返回下面的结果：

typeof true is boolean
typeof null is object

对于数值或字符串，typeof 操作符返回下面的结果：

typeof 62 is number
typeof 'Hello world' is string

对于属性值，typeof 操作符返回属性所含值的类型：

typeof document.lastModified is string
typeof window.length is number
typeof Math.LN2 is number

对于方法和函数，typeof 操作符返回下面的结果：

typeof blur is function
typeof eval is function
typeof parseInt is function
typeof shape.split is function

对于预定义对象，typeof 操作符返回下面的结果：

typeof Date is function
typeof Function is function
typeof Math is function
typeof Option is function
typeof String is function

void

void 操作符用法格式如下：

1. javascript:void (expression)
2. javascript:void expression

void 操作符指定要计算一个表达式但是不返回值。expression 是一个要计算的 JavaScript 标准的表达式。表达式外侧的圆括号是可选的，但是写上去是一个好习惯。

实现版本 Navigator 3.0

你可以使用 void 操作符指定超级链接。表达式会被计算但是不会在当前文档处装入任何内容。

下面的代码创建了一个超级链接，当用户点击以后不会发生任何事。当用户点击链接时，void(0) 计算为 0，但在 JavaScript 上没有任何效果。

<A HREF="javascript:void(0)">单击此处什么也不会发生</A>

下面的代码创建了一个超级链接，用户单击时会提交表单。

<A HREF="javascript:void(document.form.submit())">
单击此处提交表单</A>

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


JavaScript语言参考手册_实用工具

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

第十二章
实用工具

本章包含了服务器端对象 File 和 SendMail 。

表 12.1 本章用到的对象总览。

表 12 杂类对象
对象 | 描述
File | 提供了对服务器文件系统的访问。
SendMail | 提供了从 JavaScript 应用程序中发送电子邮件的功能。

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


JavaScript语言参考手册_实用工具

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

File

 Lets an application interact with a physical file on the server.

服务器端对象 |
实现版本 | LiveWire 1.0

创建源

The File constructor:

new File("path")

参数

path The path and filename in the format of the server's file system (not a URL path).

描述

You can use the File object to write to or read from a file on the server. For security reasons, you cannot programmatically access the file system of client machines.

You can use the File object to generate persistent HTML or data files without using a database server. Information stored in a file is preserved when the server goes down.

Exercise caution when using the File object. An application can read and write files anywhere the operating system allows. If you create an application that writes to or reads from your file system, you should ensure that users cannot misuse this capability.

Specify the full path, including the filename, for the path parameter of the File object you want to create. The path must be an absolute path; do not use a relative path.

If the physical file specified in the path already exists, the JavaScript runtime engine references it when you call methods for the object. If the physical file does not exist, you can create it by calling the open method.

You can display the name and path of a physical file by calling the write function and passing it the name of the related File object.

A pointer indicates the current position in a file. If you open a file in the a or a+ mode, the pointer is initially positioned at the end of the file; otherwise, it is initially positioned at the beginning of the file. In an empty file, the beginning and end of the file are the same. Use the eof, getPosition, and setPosition methods to specify and evaluate the position of the pointer. See the open method for a描述 of the modes in which you can open a file.

You can use the prototype property of the File object to add a property to all File instances. If you do so, that addition applies to all File objects running in all applications on your server, not just in the single application that made the change. This allows you to expand the capabilities of this object for your entire server.

属性概览

prototype Allows the addition of properties to a File object.

方法概览

byteToString | Converts a number that represents a byte into a string.
clearError | Clears the current file error status.
close | Closes an open file on the server.
eof | Determines whether the pointer is beyond the end of an open file.
error | Returns the current error status.
exists | Tests whether a file exists.
flush | Writes the content of the internal buffer to a file.
getLength | Returns the length of a file.
getPosition | Returns the current position of the pointer in an open file.
open | Opens a file on the server.
read | Reads data from a file into a string.
readByte | Reads the next byte from an open file and returns its numeric value.
readln | Reads the current line from an open file and returns it as a string.
setPosition | Positions a pointer in an open file.
stringToByte | Converts the first character of a string into a number that represents a byte.
write | Writes data from a string to a file on the server.
writeByte | Writes a byte of data to a binary file on the server.
writeln | Writes a string and a carriage return to a file on the server.

示例

示例 1. The following example creates the File object userInfo that refers to a physical file called info.txt. The info.txt file resides in the same directory as the application's .web file:

userInfo = new File("info.txt") 示例 2. In the following example, the File object refers to a physical file with an absolute path:

userInfo = new File("c:\\data\\info.txt") 示例 3. The following example displays the name of a File object onscreen.

userInfo = new File("c:\\data\\info.txt")
write(userInfo)

属性

prototype

 Represents the prototype for this class. You can use the prototype to add properties or methods to all instances of a class. For information on prototypes, see Function.prototype.

属性源 | File
实现版本 | LiveWire 1.0

方法

byteToString

 Converts a number that represents a byte into a string.

方法源 | File
静态 |
实现版本 | LiveWire 1.0

语法

byteToString(number)

参数

number A number that represents a byte.

描述

Use the stringToByte and byteToString methods to convert data between binary and ASCII formats. The byteToString method converts the number argument into a string.

Because byteToString is a static method of File, you always use it as File.byteToString(), rather than as a method of a File object you created.

If the argument you pass into the byteToString method is not a number, the method returns an empty string.

示例

The following example creates a copy of a text file, one character at a time. In this example, a while loop executes until the pointer is positioned past the end of the file. Inside the loop, the readByte method reads the current character from the source file, and the byteToString method converts it into a string; the write method writes it to the target file. The last readByte method positions the pointer past the end of the file, ending the while loop. See the File object for a描述 of the pointer.

// Create the source File object
source = new File("c:\data\source.txt")
// If the source file opens successfully, create a target file
if (source.open("r")) {
target = new File("c:\data\target.txt")
target.open("w")
// Copy the source file to the target
while (!source.eof()) {
data = File.byteToString(source.readByte())
target.write(data);
}
source.close()
}
target.close()
This example is similar to the example used for the write method of File. However, this example reads bytes from the source file and converts them to strings, instead of reading strings from the source file.

参看

File.stringToByte

clearError

Clears the current file error status.

方法源 | File
实现版本 | LiveWire 1.0

语法

clearError()

参数

 无。

描述

The clearError method clears both the file error status (the value returned by the error method) and the value returned by the eof method.

示例

See the example for the error method.

参看

File.error, File.eof

close

Closes an open file on the server.

方法源 | File
实现版本 | LiveWire 1.0

语法

close()

参数

 无。

描述

When your application is finished with a file, you should close the file by calling the close method. If the file is not open, the close method fails. This method returns true if it is successful; otherwise, it returns false.

示例

See the示例 for the open method.

参看

File.open, blob

eof

Determines whether the pointer is beyond the end of an open file.

方法源 | File
实现版本 | LiveWire 1.0

语法

eof()

参数

 无。

描述

Use the eof method to determine whether the position of the pointer is beyond the end of a file. See File for a描述 of the pointer.

A call to setPosition resulting in a location greater than fileObjectName.getLength places the pointer beyond the end of the file. Because all read operations also move the pointer, a read operation that reads the last byte of data (or character) in a file positions the pointer beyond the end of the file.

The eof method returns true if the pointer is beyond the end of the file; otherwise, it returns false.

示例

In this example, a while loop executes until the pointer is positioned past the end of the file. While the pointer is not positioned past the end of the file, the readln method reads the current line, and the write method displays it. The last readln method positions the pointer past the end of the file, ending the while loop.

x = new File("c:\data\userInfo.txt")
if (x.open("r")) {
while (!x.eof()) {
line = x.readln()
write(line+"<br>");
}
x.close();
}

参看

File.getPosition, File.setPosition

error

Returns the current error status.

方法源 | File
实现版本 | LiveWire 1.0

语法

error()

参数

 无

返回

0 if there is no error.

-1 if the file specified in fileObjectName is not open

Otherwise, the method returns a nonzero integer indicating the error status. Specific error status codes are platform-dependent. Refer to your operating system documentation for more information.

示例

The following example uses the error method in an if statement to take different actions depending on whether a call to the open method succeeded. After the if statement completes, the error status is reset with the clearError method.

userInput = new File("c:\data\input.txt")
userInput.open("w")
if (userInput.error() == 0) {
fileIsOpen() }
else {
fileIsNotOpen() }
userInput.clearError()

参看

File.clearError

exists

Tests whether a file exists.

方法源 | File
实现版本 | LiveWire 1.0

语法

exists()

参数

 无。

返回

True if the file exists; otherwise, false.

示例

The following example uses an if statement to take different actions depending on whether a physical file exists. If the file exists, the JavaScript runtime engine opens it and calls the writeData function. If the file does not exist, the runtime engine calls the noFile function.

dataFile = new File("c:\data\mytest.txt")
if (dataFile.exists() ==true) {
dataFile.open("w")
writeData()
dataFile.close()
}
else {
noFile()
}

flush

Writes the content of the internal buffer to a file.

方法源 | File
实现版本 | LiveWire 1.0

语法

flush()

参数

 无。

描述

When you write to a file with any of the File object methods (write, writeByte, or writeln), the data is buffered internally. The flush method writes the buffer to the physical file. The flush method returns true if it is successful; otherwise, it returns false.

Do not confuse the flush method of the File object with the top-level flush function. The flush function flushes a buffer of data and causes it to display in the client browser; the flush method flushes a buffer of data to a physical file.

示例

See the write method for an example of the flush method.

参看

File.write, File.writeByte, File.writeln

getLength

Returns the length of a file.

方法源 | File
实现版本 | LiveWire 1.0

语法

getLength()

参数

 无。

描述

If this method is successful, it returns the number of bytes in a binary file or characters in a text file; otherwise, it returns -1.

示例

The following example copies a file one character at a time. This example uses getLength as a counter in a for loop to iterate over every character in the file.

// Create the source File object
source = new File("c:\data\source.txt")
// If the source file opens successfully, create a target file
if (source.open("r")) {
target = new File("c:\data\target.txt")
target.open("a")
   // Copy the source file to the target
for (var x = 0; x < source.getLength(); x++) {
source.setPosition(x)
data = source.read(1)
target.write(data)
}
source.close()
}
target.close()

getPosition

Returns the current position of the pointer in an open file.

方法源 | File
实现版本 | LiveWire 1.0

语法

getPosition()

参数

 无

返回

-1 if there is an error.

描述

Use the getPosition method to determine the position of the pointer in a file. See the File object for a描述 of the pointer. The getPosition method returns the current pointer position; the first byte in a file is byte 0.

示例

The following示例 refer to the file info.txt, which contains the string "Hello World." The length of info.txt is 11 bytes.

示例 1. In the following example, the first call to getPosition shows that the default pointer position is 0 in a file that is opened for reading. This example also shows that a call to the read method repositions the pointer.

dataFile = new File("c:\data\info.txt")
dataFile.open("r") write("The position is " + dataFile.getPosition() + "<BR>")
write("The next character is " + dataFile.read(1) + "<BR>")
write("The new position is " + dataFile.getPosition() + "<BR>") dataFile.close() This example displays the following information:

The position is 0
The next character is H
The new position is 1 示例 2. This example uses setPosition to position the pointer one byte from the end of the eleven-byte file, resulting in a pointer position of offset 10.

dataFile = new File("c:\data\info.txt")
dataFile.open("r") dataFile.setPosition(-1,2)
write("The position is " + dataFile.getPosition() + "<BR>")
write("The next character is " + dataFile.read(1) + "<BR>") dataFile.close() This example displays the following information:

The position is 10
The next character is d 示例 3. You can position the pointer beyond the end of the file and still evaluate getPosition successfully. However, a call to eof indicates that the pointer is beyond the end of the file.

dataFile.setPosition(1,2)
write("The position is " + dataFile.getPosition() + "<BR>")
write("The value of eof is " + dataFile.eof() + "<P>") This example displays the following information:

The position is 12
The value of eof is true

参看

File.eof, File.open, File.setPosition

open

Opens a file on the server.

方法源 | File
实现版本 | LiveWire 1.0

语法

open("mode")

参数

mode A string specifying whether to open the file to read, write, or append, according to the list below.

描述

Use the open method to open a file on the server before you read from it or write to it. If the file is already open, the method fails and has no effect. The open method returns true if it is successful; otherwise, it returns false.

The mode parameter is a string that specifies whether to open the file to read, write, or append data. You can optionally use the b parameter anytime you specify the mode. If you do so, the JavaScript runtime engine on the server opens the file as a binary file. If you do not use the b parameter, the runtime engine opens the file as a text file. The b parameter is available only on Windows platforms.

The possible values for mode are as follows:

  • r[b] opens a file for reading. If the file exists, the method succeeds and returns true; otherwise, the method fails and returns false.

  • w[b] opens a file for writing. If the file does not already exist, it is created; otherwise, it is overwritten. This method always succeeds and returns true.

  • a[b] opens a file for appending (writing at the end of the file). If the file does not already exist, it is created. This method always succeeds and returns true.

  • r+[b] opens a file for reading and writing. If the file exists, the method succeeds and returns true; otherwise, the method fails and returns false. Reading and writing commence at the beginning of the file. When writing, characters at the beginning of the file are overwritten.

  • w+[b] opens a file for reading and writing. If the file does not already exist, it is created; otherwise, it is overwritten. This method always succeeds and returns true.

  • a+[b] opens a file for reading and appending. If the file does not already exist, it is created. This method always succeeds and returns true. Reading and appending commence at the end of the file.
When your application is finished with a file, you should close the file by calling the close method.

示例

示例 1. The following example opens the file info.txt so an application can write information to it. If info.txt does not already exist, the open method creates it; otherwise, the open method overwrites it. The close method closes the file after the writeData function is completed.

userInfo = new File("c:\data\info.txt")
userInfo.open("w")
writeData()
userInfo.close()
示例 2. The following example opens a binary file so an application can read data from it. The application uses an if statement to take different actions depending on whether the open statement finds the specified file.

entryGraphic = new File("c:\data\splash.gif")
if (entryGraphic.open("rb") == true) {
displayProcedure()
}
else {
errorProcedure()
}
entryGraphic.close()

参看

File.close

read

Reads data from a file into a string.

方法源 | File
实现版本 | LiveWire 1.0

语法

read(count)

参数

count An integer specifying the number of characters to read.

描述

The read method reads the specified number of characters from a file, starting from the current position of the pointer. If you attempt to read more characters than the file contains, the method reads as many characters as possible. This method moves the pointer the number of characters specified by the count parameter. See the File object for a描述 of the pointer.

The read method returns the characters it reads as a string.

Use the read method to read information from a text file; use the readByte method to read data from a binary file.

示例

The following example references the file info.txt, which contains the string "Hello World." The first read method starts from the beginning of the file and reads the character "H." The second read method starts from offset six and reads the characters "World."

dataFile = new File("c:\data\info.txt")
dataFile.open("r") write("The next character is " + dataFile.read(1) + "<BR>")
dataFile.setPosition(6)
write("The next five characters are " + dataFile.read(5) + "<BR>") dataFile.close() This example displays the following information:

The next character is H
The next five characters are World

参看

File.readByte, File.readln, File.write

readByte

Reads the next byte from an open file and returns its numeric value.

方法源 | File
实现版本 | LiveWire 1.0

语法

readByte()

参数

 无。

描述

The readByte method reads the next byte from a file, starting from the current position of the pointer. This method moves the pointer one byte. See the File object for a描述 of the pointer.

The readByte method returns the byte it reads as a number. If the pointer is at the end of the file when you issue readByte, the method returns -1.

Use the readByte method to read information from a binary file. You can use the readByte method to read from a text file, but you must use the byteToString method to convert the value to a string. Generally it is better to use the read method to read information from a text file.

You can use the writeByte method to write data read by the readByte method to a file.

示例

This example creates a copy of a binary file. In this example, a while loop executes until the pointer is positioned past the end of the file. While the pointer is not positioned past the end of the file, the readByte method reads the current byte from the source file, and the writeByte method writes it to the target file. The last readByte method positions the pointer past the end of the file, ending the while loop.

// Create the source File object
source = new File("c:\data\source.gif")
// If the source file opens successfully, create a target file
if (source.open("rb")) {
target = new File("c:\data\target.gif")
target.open("wb")
// Copy the source file to the target
while (!source.eof()) {
data = source.readByte()
target.writeByte(data);
}
source.close();
}
target.close()

参看

File.read, File.readln, File.writeByte

readln

Reads the current line from an open file and returns it as a string.

方法源 | File
实现版本 | LiveWire 1.0

语法

readln()

参数

 无

描述

The readln method reads the current line of characters from a file, starting from the current position of the pointer. If you attempt to read more characters than the file contains, the method reads as many characters as possible. This method moves the pointer to the beginning of the next line. See the File object for a描述 of the pointer.

The readln method returns the characters it reads as a string.

The line separator characters ("\r" and "\n" on Windows platforms and "\n" on UNIX platforms) are not included in the string that the readln method returns. The \r character is skipped; \n determines the actual end of the line.

Use the readln method to read information from a text file; use the readByte method to read data from a binary file. You can use the writeln method to write data read by the readln method to a file.

示例

See File.eof

参看

File.read, File.readByte, File.writeln

setPosition

Positions a pointer in an open file.

方法源 | File
实现版本 | LiveWire 1.0

语法

setPosition(position, reference)

参数

position | An integer indicating where to position the pointer.
reference | (Optional) An integer that indicates a reference point, according to the list below.

描述

Use the setPosition method to reposition the pointer in a file. See the File object for a描述 of the pointer.

The position argument is a positive or negative integer that moves the pointer the specified number of bytes relative to the reference argument. Position 0 represents the beginning of a file. The end of a file is indicated by fileObjectName.getLength().

The optional reference argument is one of the following values, indicating the reference point for position:

  • 0: relative to beginning of file.
    •
  • 1: relative to current position.
    •
  • 2: relative to end of file.
    •
  • Other (or unspecified): relative to beginning of file.
The setPosition method returns true if it is successful; otherwise, it returns false.

示例

The following示例 refer to the file info.txt, which contains the string "Hello World." The length of info.txt is 11 bytes. The first example moves the pointer from the beginning of the file, and the second example moves the pointer to the same location by navigating relative to the end of the file. Both示例 display the following information:

The position is 10
The next character is d 示例 1. This example moves the pointer from the beginning of the file to offset 10. Because no value for reference is supplied, the JavaScript runtime engine assumes it is 0.

dataFile = new File("c:\data\info.txt")
dataFile.open("r") dataFile.setPosition(10)
write("The position is " + dataFile.getPosition() + "<BR>")
write("The next character is " + dataFile.read(1) + "<P>") dataFile.close() 示例 2. This example moves the pointer from the end of the file to offset 10.

dataFile = new File("c:\data\info.txt")
dataFile.open("r")
dataFile.setPosition(-1,2)
write("The position is " + dataFile.getPosition() + "<BR>")
write("The next character is " + dataFile.read(1) + "<P>")
dataFile.close()

参看

File.eof, File.getPosition, File.open

stringToByte

Converts the first character of a string into a number that represents a byte.

方法源 | File
静态 |
实现版本 | LiveWire 1.0

语法

stringToByte(string)

参数

string A JavaScript string.

描述

Use the stringToByte and byteToString methods to convert data between binary and ASCII formats. The stringToByte method converts the first character of its string argument into a number that represents a byte.

Because stringToByte is a static method of File, you always use it as File.stringToByte(), rather than as a method of a File object you created.

If this method succeeds, it returns the numeric value of the first character of the input string; if it fails, it returns 0.

示例

In the following example, the stringToByte method is passed "Hello" as an input argument. The method converts the first character, "H," into a numeric value representing a byte.

write("The stringToByte value of Hello = " +
File.stringToByte("Hello") + "<BR>")
write("Returning that value to byteToString = " +
File.byteToString(File.stringToByte("Hello")) + "<P>")
The previous example displays the following information:

The stringToByte value of Hello = 72
Returning that value to byteToString = H

参看

File.byteToString

write

Writes data from a string to a file on the server.

方法源 | File
实现版本 | LiveWire 1.0

语法

write(string)

参数

string A JavaScript string.

描述

The write method writes the string specified as string to the file specified as fileObjectName. This method returns true if it is successful; otherwise, it returns false.

Use the write method to write data to a text file; use the writeByte method to write data to a binary file. You can use the read method to read data from a file to a string for use with the write method.

Do not confuse the write method of the File object with the write function. The write function outputs data to the client browser; the write method outputs data to a physical file on the server.

示例

This example creates a copy of a text file, one character at a time. In this example, a while loop executes until the pointer is positioned past the end of the file. While the pointer is not positioned past the end of the file, the read method reads the current character from the source file, and the write method writes it to the target file. The last read method positions the pointer past the end of the file, ending the while loop. See the File object for a描述 of the pointer.

// Create the source File object
source = new File("c:\data\source.txt")
// If the source file opens successfully, create a target file
if (source.open("r")) {
target = new File("c:\data\target.txt")
target.open("w")
// Copy the source file to the target
while (!source.eof()) {
data = source.read(1)
target.write(data);
}
source.close();
}
target.flush()
target.close()

参看

File.flush, File.read, File.writeByte, File.writeln

writeByte

Writes a byte of data to a binary file on the server.

方法源 | File
实现版本 | LiveWire 1.0

语法

writeByte(number)

参数

number A number that specifies a byte of data.

描述

The writeByte method writes a byte that is specified as number to a file that is specified as fileObjectName. This method returns true if it is successful; otherwise, it returns false.

Use the writeByte method to write data to a binary file; use the write method to write data to a text file. You can use the readByte method to read bytes of data from a file to numeric values for use with the writeByte method.

示例

See the example for the readByte method.

参看

File.flush, File.readByte, File.write, File.writeln

writeln

Writes a string and a carriage return to a file on the server.

方法源 | File
实现版本 | LiveWire 1.0

语法

writeln(string)

参数

string A JavaScript string.

描述

The writeln method writes the string specified as string to the file specified as fileObjectName. Each string is followed by the carriage return/line feed character "\n" ("\r\n" on Windows platforms). This method returns true if the write is successful; otherwise, it returns false.

Use the writeln method to write data to a text file; use the writeByte method to write data to a binary file. You can use the readln method to read data from a file to a string for use with the writeln method.

示例

This example creates a copy of a text file, one line at a time. In this example, a while loop executes until the pointer is positioned past the end of the file. While the pointer is not positioned past the end of the file, the readln method reads the current line from the source file, and the writeln method writes it to the target file. The last readln method positions the pointer past the end of the file, ending the while loop. See the File object for a描述 of the pointer.

// Create the source File object
source = new File("c:\data\source.txt")
// If the source file opens successfully, create a target file
if (source.open("r")) {
target = new File("c:\data\target.txt")
target.open("w")
// Copy the source file to the target
while (!source.eof()) {
data = source.readln()
target.writeln(data);
}
source.close();
}
target.close()
Note that the readln method ignores the carriage return/line feed characters when it reads a line from a file. The writeln method appends these characters to the string that it writes.

参看

File.flush, File.readln, File.write, File.writeByte


JavaScript语言参考手册_实用工具

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

SendMail

 Sends an email message.

服务器端对象 |
实现版本 | Netscape Server 3.0

The To and From attributes are required. All other properties are optional.

创建源

The SendMail constructor:

new SendMail();

参数

无。

描述

Whatever properties you specify for the SendMail object are sent in the header of the mail message.

The SendMail object allows you to send either simple text-only mail messages or complex MIME-compliant mail or add attachments to your message. To send a MIME message, set the Content-Type property to the MIME type of the message.

You can use the prototype property of the SendMail object to add a property to all SendMail instances. If you do so, that addition applies to all SendMail objects running in all applications on your server, not just in the single application that made the change. This allows you to expand the capabilities of this object for your entire server.

属性概览

Bcc | Comma-delimited list of recipients of the message whose names should not be visible in the message.
Body | Text of the message.
Cc | Comma-delimited list of additional recipients of the message.
Errorsto | Address to which to send errors concerning the message. Defaults to the sender's address.
From | User name of the person sending the message.
Organization | Organization information.
prototype | Allows the addition of properties to a SendMail object.
Replyto | User name to which replies to the message should be sent. Defaults to the sender's address.
Smtpserver | Mail (SMTP) server name. Defaults to the value specified through the setting in the Administration server.
Subject | Subject of the message.
To | Comma-delimited list of primary recipients of the message.

方法概览

errorCode | Returns an integer error code associated with sending this message.
errorMessage | Returns a string associated with sending this message.
send | Sends the mail message represented by this object.

示例

示例 1: The following script sends mail to vpg and gwp, copying jaym, with the specified subject and body for the message:

<server>
SMName = new SendMail();
SMName.To = "vpg@co1.com, gwp@co2.com"
SMName.From = "me@myco.com"
SMName.Cc = "jaym@hisco.com"
SMName.Subject = "The State of the Universe"
SMName.Body = "The universe, contrary to what you may have heard, is in none too shabby shape. Not to worry! --me"
SMName.send()
</server>
示例 2: The following example sends an image in a GIF file:

sm = new SendMail();
sm.To = "satish";
sm.From = "satish@netscape.com";
sm.Smtpserver = "fen.mcom.com";
sm["Errors-to"] = "satish";
sm["Content-type"] = "image/gif";
sm["Content-Transfer-Encoding"] = "base64";
file = new File("/u/satish/LiveWire/mail/banner.gif");
openFlag = file.open("r");
if ( openFlag ) {
len = file.getLength();
str = file.read(len);
sm.Body = str;
}
sm.send();
示例 3: The following example sends a multipart message:

sm = new SendMail();
sm.To = "chandra@cs.uiowa.edu, satish@netscape.com";
sm.From = "satish@netscape.com";
sm.Smtpserver = "fen.mcom.com";
sm.Organization = "Netscape Comm Corp";
sm["Content-type"] = "multipart/mixed; boundary=\"------------8B3F7BA67B67C1DDE6C25D04\"";
file = new File("/u/satish/LiveWire/mail/mime");
openFlag = file.open("r");
if ( openFlag ) {
len = file.getLength();
str = file.read(len);
sm.Body = str;
}
sm.send();
The file mime has HTML text and an Microsoft Word document separated by the specified boundary. The resulting message appears as HTML text followed by the Microsoft Word attachment.

属性

Bcc

 Comma-delimited list of recipients of the message whose names should not be visible in the message.

属性源 | SendMail
实现版本 | Netscape Server 3.0

Body

Text of the message.

属性源 | SendMail
实现版本 | Netscape Server 3.0

Cc

Comma-delimited list of additional recipients of the message.

属性源 | SendMail
实现版本 | Netscape Server 3.0

Errorsto

Address to which to send errors concerning the message. Defaults to the sender's address.

属性源 | SendMail
实现版本 | Netscape Server 3.0

From

User name of the person sending the message.

属性源 | SendMail
实现版本 | Netscape Server 3.0

Organization

Organization information.

属性源 | SendMail
实现版本 | Netscape Server 3.0

prototype

Represents the prototype for this class. You can use the prototype to add properties or methods to all instances of a class. For information on prototypes, see Function.prototype.

属性源 | SendMail
实现版本 | LiveWire 1.0

Replyto

User name to which replies to the message should be sent. Defaults to the sender's address.

属性源 | SendMail
实现版本 | Netscape Server 3.0

Smtpserver

Mail (SMTP) server name. Defaults to the value specified through the setting in the Administration server.

属性源 | SendMail
实现版本 | Netscape Server 3.0

Subject

Subject of the message.

属性源 | SendMail
实现版本 | Netscape Server 3.0

To

Comma-delimited list of primary recipients of the message.

属性源 | SendMail
实现版本 | Netscape Server 3.0

方法

errorCode

 Returns an integer error code associated with sending this message.

方法源 | SendMail
实现版本 | Netscape Server 3.0

语法

public errorCode();

返回

 The possible return values and their meanings are as follows:

0 | Successful send.
1 | SMTP server not specified.
2 | Specified mail server is down or doesn't exist.
3 | At least one receiver's address must be specified to send the message.
4 | Sender's address must be specified to send the message.
5 | Mail connection problem; data not sent.

errorMessage

Returns a string associated with sending this message.

方法源 | SendMail
实现版本 | Netscape Server 3.0

语法

public errorMessage();

返回

 An error string.

send

Sends the mail message represented by this object.

方法源 | SendMail
实现版本 | Netscape Server 3.0

语法

public send ();

返回

 This method returns a Boolean value to indicate whether or not the mail was successfully sent. If the mail was not successfully sent, you can use the errorMessage and errorCode methods to determine the nature of the error.

This method returns a string indicating the nature of the error that occurred sending the message.

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


JavaScript语言参考手册_LiveConnect 的 Java 包

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

第十四章
LiveConnect 的 Java 包

LiveConnect 工具允许你的 JavaScript 应用程序与 Java 对象协同工作，以及允许那些 Java 对象与 JavaScript 的对象协同工作。

LiveConnect 提供了两个 Java 小程序的 API 包用于与 JavaScript 互相通讯。这些包是 netscape.javascript 和 netscape.plugin 。

netscape.javascript 小程序包在客户端和服务器端都可用，其中包含下列类：

  • netscape.javascript.JSObject
  • netscape.javascript.JSException
netscape.plugin 小程序 API 包只能在客户端使用，其中包含下列类：

  • netscape.plugin.Plugin
以下节描述了这些类并列出了它们的构造函数和方法。

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


JavaScript语言参考手册_LiveConnect 的 Java 包

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

netscape.javascript.JSObject

 The public final class JSObject extends Object.

java.lang.Object
|
+----netscape.javascript.JSObject JSObject allows Java to manipulate objects that are defined in JavaScript. Values passed from Java to JavaScript are converted as follows:

  • JSObject is converted to the original JavaScript object.

  • Any other Java object is converted to a JavaScript wrapper, which can be used to access methods and fields of the Java object. Converting this wrapper to a string will call the toString method on the original object, converting to a number will call the floatValue method if possible and fail otherwise. Converting to a boolean will try to call the booleanValue method in the same way.

  • Java arrays are wrapped with a JavaScript object that understands array.length and array【索引】.

  • A Java boolean is converted to a JavaScript boolean.

  • Java byte, char, short, int, long, float, and double are converted to JavaScript numbers.
Values passed from JavaScript to Java are converted as follows:

  • Objects that are wrappers around Java objects are unwrapped.

  • Other objects are wrapped with a JSObject.

  • Strings, numbers, and booleans are converted to String, Float, and Boolean objects respectively.
This means that all JavaScript values show up as some kind of java.lang.Object in Java. In order to make much use of them, you will have to cast them to the appropriate subclass of Object, as shown in the following示例:

(String) window.getMember("name")
(JSObject) window.getMember("document")

Note If you call a Java method from JavaScript, this conversion happens automatically--you can pass in "int" argument and it works.

方法 and static方法

 The netscape.javascript.JSObject class has the following methods:

表 14.1 Methods for the JSObject class
Method | 描述
call | Calls a JavaScript 方法
eval | Evaluates a JavaScript expression
getMember | Retrieves a named member of a JavaScript object
getSlot | Retrieves an indexed member of a JavaScript object
removeMember | Removes a named member of a JavaScript object
setMember | Sets a named member of a JavaScript object
setSlot | Sets an indexed member of a JavaScript object
toString | Converts a JSObject to a string

The netscape.javascript.JSObject class has the following static methods:

表 14.2 Static methods for the JSObject class
Method | 描述
getWindow | Gets a JSObject for the window containing the given applet

The following sections show the declaration and usage of these methods.

call

Method. Calls a JavaScript method. Equivalent to "this.methodName(args[0], args[1], ...)" in JavaScript.

Declaration

public Object call(String methodName,
Object args[])

eval

 Method. Evaluates a JavaScript expression. The expression is a string of JavaScript source code which will be evaluated in the context given by "this".

Declaration

public Object eval(String s)

getMember

 Method. Retrieves a named member of a JavaScript object. Equivalent to "this.name" in JavaScript.

Declaration

public Object getMember(String name)

getSlot

 Method. Retrieves an indexed member of a JavaScript object. Equivalent to "this【索引】" in JavaScript.

Declaration

public Object getSlot(int index)

getWindow

 Static method. Returns a JSObject for the window containing the given applet. This method is available only on the client.

Declaration

public static JSObject getWindow(Applet applet)

removeMember

 Method. Removes a named member of a JavaScript object.

Declaration

public void removeMember(String name)

setMember

 Method. Sets a named member of a JavaScript object. Equivalent to "this.name = value" in JavaScript.

Declaration

public void setMember(String name,
Object value)

setSlot

 Method. Sets an indexed member of a JavaScript object. Equivalent to "this【索引】 = value" in JavaScript.

Declaration

public void setSlot(int index,
Object value)

toString

 Method. Converts a JSObject to a String.

Overrides: toString in class Object

Declaration

public String toString()


JavaScript语言参考手册_LiveConnect 的 Java 包

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

netscape.javascript.JSException

 The public class JSException extends Exception.

java.lang.Object
|
+----java.lang.Throwable
|
+----java.lang.Exception
|
+----netscape.javascript.JSException JSException is an exception that is thrown when JavaScript code returns an error.

Constructors

The netscape.javascript.JSException class has the following constructors:

表 14.3 Constructors for the JSException class
Constructor | 描述
JSException | Constrqcts a JSException. You specify whether the JSException has a detail message and other information.

The following sections show the declaration and usage of these constructors.

JSException

Constructor. Constructs a JSException. You specify whether the JSException has a detail message and other information.

Declaration

1. public JSException() 2. public JSException(String s) 3. public JSException(String s,
String filename,
int lineno,
String source,
int tokenIndex)

参数

s | The detail message.
filename | The URL of the file where the error occurred, if possible.
lineno | The line number if the file, if possible.
source | The string containing the JavaScript code being evaluated.
tokenIndex | The index into the source string where the error occurred.

描述

A detail message is a string that describes this particular exception.

Each form constructs a JSException with different information:

  • Form 1 of the declaration constructs a JSException without a detail message.

  • Form 2 of the declaration constructs a JSException with a detail message.

  • Form 3 of the declaration constructs a JSException with a detail message and all the other information that usually comes with a JavaScript error.


JavaScript语言参考手册_LiveConnect 的 Java 包

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

netscape.plugin.Plugin

 The public class Plugin extends Object.

java.lang.Object
|
+----netscape.plugin.Plugin This class represents the Java reflection of a plug-in. Plug-ins that need to have Java methods associated with them should subclass this class and add new (possibly native) methods to it. This allows other Java entities (such as applets and JavaScript code) to manipulate the plug-in.

Constructors and方法

The netscape.plugin.Plugin class has the following constructors:

表 14.4 Constructors for the Plugin class
Constructor | 描述
Plugin | Constructs a Plugin.

The netscape.plugin.Plugin class has the following methods:

表 14.5 Methods for the Plugin class
Method | 描述
destroy | Called when the plug-in is destroyed
getPeer | Returns the native NPP object--the plug-in instance that is the native part of a Java Plugin object
getWindow | Returns the JavaScript window on which the plug-in is embedded
init | Called when the plug-in is initialized
isActive | Determines whether the Java reflection of a plug-in still refers to an active plug-in

The following sections show the declaration and usage of these constructors and methods.

destroy

Method. Called when the plug-in is destroyed. You never need to call this method directly, it is called when the plug-in is destroyed. At the point this method is called, the plug-in will still be active.

Declaration

public void destroy()

参看

 init

getPeer

Method. Returns the native NPP object--the plug-in instance that is the native part of a Java Plugin object. This field is set by the system, but can be read from plug-in native methods by calling:

NPP npp = (NPP)netscape_plugin_Plugin_getPeer(env, thisPlugin);

Declaration

public int getPeer()

getWindow

 Method. Returns the JavaScript window on which the plug-in is embedded.

Declaration

public JSObject getWindow()

init

 Method. Called when the plug-in is initialized. You never need to call this method directly, it is called when the plug-in is created.

Declaration

public void init()

参看

 destroy

isActive

Method. Determines whether the Java reflection of a plug-in still refers to an active plug-in. Plug-in instances are destroyed whenever the page containing the plug-in is left, thereby causing the plug-in to no longer be active.

Declaration

public boolean isActive()

Plugin

 Constructor. Constructs a Plugin.

Declaration

public Plugin()

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


JavaScript语言参考手册_轻松上手

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

轻松上手

本书是 JavaScript 语言的参考手册，包括核心语言中的对象和客户端、服务器端的扩展。JavaScript 是 Netscape 跨平台的基于对象的适合于客户和服务器的脚本语言。

  • 你应该已经知道的东西
  • 在哪里能找到 JavaScript 信息
  • 文档规范

你应该已经知道的东西

 本书假定你有以下基础：

  • 对于 Internet 和万维网 (WWW) 的基本了解。

  • 对于超文本标记语言 (HTML) 的良好掌握。最好有应用表单和通用网关接口 (CGI) 编程的经验。

  • 如果你将要使用 LiveWire 数据库服务，那么就需要有与数据库相关的知识和结构化查询语言 (SQL) 的良好掌握。

在哪里能找到 JavaScript 信息

 因为 JavaScript 是分成几层按级实现的，它的文档就要分成好几本书以便适应不同人的需要。在线 JavaScript 参考的完美组合包括：

  • JavaScript 指南提供了关于核心 JavaScript 语言及客户端对象的信息。

  • 编写服务器端 JavaScript 应用程序提供了关于 JavaScript 的服务器对象和函数的信息。在某些情况下，核心语言的特性在客户端和服务器端上运行不同。这些不同也在该书中有详细讨论。最后，这本书提供了你需要用于创建一个完整的 JavaScript 应用程序的额外信息。

  • JavaScript 参考 (本书) 提供了整个 JavaScript 语言，包括客户端和服务器端 JavaScript 的参考材料。

  • DevEdge 库的 JavaScript 页包含了一些其它与 JavaScript 有关的文档。该页的内容是时刻更新的。你应该适时访问它以便获得最新信息。
另外，其它的 Netscape 书也将在各自的专题范围之内讨论与之有关的 JavaScript。

Netscape 网站包含了在你创建 JavaScript 应用程序时十分有用的大量信息。这些你可能感兴趣的 URL 包括：

  • http://home.netscape.com/one_stop/intranet_apps/index.html
    • 这是 Netscape AppFoundry Online 的主页。Netscape AppFoundry Online 是应用程序起始之源、技术信息、工具和用于快速创建和动态发布开放的 Intranet 应用程序的专家论坛。该站在资源区中包括解决问题的信息，以及设置 JavaScript 环境的额外帮助。

  • http://help.netscape.com/products/tools/livewire
    • 这是 Netscape 的 LiveWire 数据库服务的技术支持页。它包含了关于在你的 JavaScript 应用程序中使用 LiveWire 的大量使用的信息。

  • http://developer.netscape.com/library/one/sdk/livewire/
    • 这是 Netscape 的服务器端 JavaScript 支持页。单击 Netscape 服务器应用程序管理器的文档链接也可访问该页。

文档规范

 本书的某些地方会告诉你如何在 Netscape Navigator 的用户界面中找到一些东西。在这种情况下，本书是以 Navigator 4.0 的用户界面作为基准描述的。显然，用户界面可能在先前版本的浏览器中有些不同。

JavaScript 应用程序可在许多操作系统中运行；此处的信息应该适用于所有版本。文件和目录路径是以 Windows 格式 (用反斜线分隔目录名) 给出的。对于 Unix 版本，目录路径是相同的，只是你应该使用斜线来替代反斜线分隔目录。

本书以下面的格式使用使用统一资源定位符 (URL)

http://server.domain/path/file.html 在这些 URL 中，server 代表你运行应用程序的服务器名，如 research1 或 www ；domain 代表你的 Internet 域名，如 netscape.com 或 uiuc.edu ；path 代表服务器上的目录结构；而 file.html 代表单独的文件名。在通常情况下，URL 中斜体的内容通常位占位符，而标准体则代表实际的字面意义。如果你的服务器允许安全套接层 (SSL)，你也许应该在 URL 中使用 https 来代替 http。

本书使用下面的字体规范：

  • 打字机字体用于示例代码和代码清单，API 和语言元素(如函数名称和类名称)，文件名，路径名，目录名，HTML 标签和其它任何将要在屏幕上打出的文字。(打字机字体的斜体用于代码中嵌入的占位符。)

  • 斜体字用于书标题、强调、变量和占位符，以及代表字面含义的词语。

  • 粗体字用于词汇声明。

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


JavaScript语言参考手册_索引

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

Index

Note: This index has not yet been updated.

Symbols

! operator 66
# (hash mark in URL) 254
% operator 62
& operator 63
&& operator 66
*/ comment 78
-- operator 63
++ operator 62
/* comment 78
// comment 78
^ operator 63
| operator 63
|| operator 66
~ operator 63

A

A HTML tag 277
abort event 499
about: (URL语法) 346, 347
abs method 141
acos method 142
action property 376
addClient function 669
agent property 620
alert method 317
alinkColor property 226
anchor method 174
Anchor object 262
anchors
Anchor object 262
creating 174
animation 266
appCodeName property 474
APPLET HTML tag 276
Applet object 276
applets
including in a web page 276
appName property 475
appVersion property 475
AREA HTML tag 277
Area object 249, 261
arguments array 130
arithmetic operators
decrement 62
increment 62
modulus 62
unary negation 63
Array object 94
arrays
Array object 94
creating from strings 192
dense 95
increasing length of 94
indexing 95
initial length of 94
joining 100
length of, determining 98, 173, 363, 377
referring to elements 95
sorting 106
asin method 143
assignment operators 60
atan method 143
atan2 method 144
AUTH_TYPE CGI variable 687

B

back method 318, 365
background color 280
beginTransaction method
of Connection objects 533, 571
bgColor property 228, 280
BIG HTML tag 175
big method 175
binary data, converting to string 642
bitwise operators
logical 64
overview 63
shift 65
BLINK HTML tag 175
blink method 175
blob function 671
Blob objects 610-614
blobImage method 611
blobLink method 613
blobImage method
of Blob objects 611
blobLink method
of Blob objects 613
BOLD HTML tag 176
bold method 176
Boolean object 111
border property 270
break statement 77
browser
about: (URL语法) 347
code name of 474
name of 475
Button object 416
buttons
Button object 416
clicking programmatically 428, 435, 445
submit 423
bytes, converting to string 642
byteToString method 642

C

C functions
calling 667
registering 668
caching graphics 266
call method (LiveConnect) 697
callC function 672
caller property 132
ceil method 145
CGI programs, and LiveWire xliii
CGI variables
AUTH_TYPE 687
HTTPS 687
HTTPS_KEYSIZE 687
HTTPS_SECRETKEYSIZE 687
PATH_TRANSLATED 687
QUERY_STRING 687
REMOTE_ADDR 687
REMOTE_HOST 687
REMOTE_USER 687
REQUEST_METHOD 687
SCRIPT_NAME 687
SERVER_NAME 688
SERVER_PORT 688
SERVER_PROTOCOL 688
SERVER_URL 688
charAt method 177
Checkbox object 446
checkboxes
Checkbox object 446
clicking programmatically 428, 435, 445
default selection state 441
defining 446
clearError method 643
clearInterval method 320
client
preserving properties 669
client JavaScript 49
client object 625
getting identifier 668, 688
maintaining 667
storing properties on project or server ??-689
uniquely referring to ??-689
close method
document object 241
File object 644
window object 321
closed property 301
colors
background 280
comment statement 78
comments 78
comparison operators 61
complete property 270
confirm method 322
connection method
of DbPool objects 562
Connection objects ??-553, ??-569, 570-588
beginTransaction method 533, 571
scope 554
constructor property 161
containership
specifying default object 90
with statement and 90
continue statement 78
conventions 75
cookie property 228
cos method 146
cosine 146
creating 668, 688
current property 363
cursor method 539, 575
Cursor objects 588-??
deleteRow method 594
insertRow method 595
next method 597, 609
properties 590
See also cursors.
updateRow method 598

D

database object 530
Date object 113
dates
converting to string 125
Date object 113
day of week 116
defining 113
milliseconds since 1970 126
month 117
DbPool objects 553-??
connection method 562
disconnect method 542, 562
storedProcArgs method 551, 567
debug function 673
decrement operator 62
default objects, specifying 90
defaultChecked property 441, 449
defaultSelected property 467
defaultStatus property 302
deleteRow method
of Cursor objects 594
dense arrays 95
destroy method 627
destroy method (LiveConnect) 702
dialog boxes
Confirm 322
Prompt 333
directories
conventions used xlv
disconnect method
of DbPool objects 542, 562
DNS 687
document conventions ??-xlv
document object 222
embeds array 231
documents
color of 280
document object 222
embeds array 231
domain property 230

E

E property 138
elements array 376
embeds array 231
enabledPlugin property 484
encoding property 377
ENCTYPE attribute 377
environment variables
accessing 687
eof method 644
error method 645
errors
status 641, 643
escape function 674
Euler's constant 138
raised to a power 146
eval method 162, 675
eval method (LiveConnect) 698
event handlers 499-??
defining 493
event object 497
in Function objects 129
specifying object names in 321
event object 497
events
event object 497
handling specific 242, 260, 275, 326, 379, 393, 402, 409, 415, 422, 429, 436, 446, 453, 463
events, defined 493
exists method 646
exp method 146
expiration method 628
expressions
that return no value 73

F

fgColor property 232
File object 639
file: (URL语法) 346
filename property 489
files
error status 641, 643
FileUpload object 410
find method 324
fixed method 179
floor method 147
flush function 677
described 677
flush method 647
focus
removing 319, 392, 401, 421, 424, 428, 435, 444, 463
focus method 325, 393, 401, 408, 414, 422, 429, 436, 445, 452, 463
fontcolor method 180
fonts
big 175
blinking 175
bold 176
fontsize method 181
for loops
continuation of 78
syntax of 82
termination of 77
for statement 82
for...in statement 83
FORM HTML tag 372
Form object 372
elements array 376
form property 383, 388, 397, 405, 412, 417, 425, 432, 442, 450, 458
forms
checkboxes 446
defining 372
element focus 319, 392, 401, 421, 424, 428, 435, 444, 463
element names 307, 378, 390, 399, 450
elements array 376
ENCTYPE attribute 377
Form object 372
and LiveWire xliii
MIME encoding 377
submit buttons 423
submitting 423
Forward button 325
forward method 325, 366
Frame object 344
frames
Frame object 344
top 285, 315
ftp: (URL语法) 346
Function object 126
specifying arguments for 128
specifying event handler with 129
as variable value 127
function statement 83
functions 141-??
addClient 669
arguments array 130
blob 671
callC 672
caller property 132
calling external 672
debug 673
escape 674
flush 677
Function object 126
isNAN 680
number of arguments 98, 173, 363, 377
parseFloat 627, 681
parseInt 627, 682
redirect 684
registerCFunction 685
return values of 87
unescape 691
as variable value 127
write 693

G

getDate method 115
getDay method 116
getHours method 116
getLength method 647
getMember method (LiveConnect) 698
getMinutes method 117
getMonth method 117
getOptionValue property 678
getPeer method (LiveConnect) 702
getPosition method 648
getSeconds method 118
getSelection method 242
getSlot method (LiveConnect) 698
getTime method 118
getTimezoneOffset method 119
getWindow method (LiveConnect) 702
getWindow static method (LiveConnect) 698
getYear method 119
Go menu 361
go method 366
gopher: (URL语法) 346

H

handleEvent method 242, 260, 275, 326, 379, 393, 402, 409, 415, 422, 429, 436, 446, 453, 463
handling specific events 242, 260, 275, 326, 379, 393, 402, 409, 415, 422, 429, 436, 446, 453, 463
height property 271
Hidden object 382
history list
next URL in 325
history object 361
current property 363
next property 364
previous property 364
home method 327
host property 633
hostname 688
hostname property 256, 351, 634
href property 256, 352
hspace property 272
HTML
generated 247
generating 668
and Livewire xliii
HTML tags
A 277
APPLET 276
AREA 277
BIG 175
BLINK 175
BOLD 176
FORM 372
IMG 612
INPUT 423, 446
MAP 277
HTTP method 687
HTTP protocol level 688
HTTP user 687
http: (URL语法) 346
HTTPS CGI variable 687
HTTPS_KEYSIZE CGI variable 687
HTTPS_SECRETKEYSIZE CGI variable 687

I

if...else statement 84
Image object 264
images
and animation 266
Area object 249
border 270
caching 266
preloading 266
size of 265
source 285
imageX property 621, 622
imageY property 622
IMG HTML tag 612
increment operator 62
indexOf method 183
init method (LiveConnect) 703
INPUT HTML tag 423, 446
inputName property 623
insertRow method
of Cursor objects 595
ip property 623
isActive method (LiveConnect) 703
isNaN function 680
italics method 184

J

javaEnabled method 480
JavaScript
debugging 667
LiveWire 50-52
Navigator 49-50
javascript: (URL语法) 346, 347
join method 100
JSException class 699
JSException constructor (LiveConnect) 700
JSObject class 695

L

lastIndexOf method 185
lastModified property 234
Layer object 277
layers 277
left shift operator 65
link method 186
Link object 249
linkColor property 236
links
anchors for 174
and areas 277
for BLOb data 611, 613
defining 277
and images 277
Link object 249
with no destination 73
lists, selection 453
LiveConnect
packages 695-703
LiveWire
background for using xliii
LN10 property 138
LN2 property 139
load event 515
location object 344
location property 239
log method 148
LOG10E property 139
LOG2E property 140
logarithms
base of natural 138, 146
natural logarithm of 10 138
logical operators
overview 66
short-circuit evaluation 67
loops
continuation of 78
for 82
termination of 77
while 89
lowercase 172, 200
lowsrc property 272

M

mailto: (URL语法) 346
MAP HTML tag 277
Math object 136
max method 148
MAX_VALUE property 155
MAYSCRIPT attribute 276
messages
Confirm dialog box 322
Prompt dialog box 333
method property 378, 624
methods 141-??
MIME encoding 377
MIME types
configured plug-in for 484
plug-ins supported 486
MimeType object 482
min method 149
MIN_VALUE property 156
modulo function 62
modulus operator 62
mouseout event 519
mouseOver event 520
moveBy method 327
moveTo method 288, 328
multimedia
and blobLink 613

N

name property 272, 283, 307, 378, 384, 390, 399, 406, 412, 419, 426, 432, 442, 450, 459, 489
NaN property 156
natural logarithms
base of 138
e 138
e raised to a power 146
of 10 138
Navigator
about: (URL语法) 347
code name of 474
and JavaScript 49, 50
name of 475
navigator object 473
NEGATIVE_INFINITY property 157
netscape.javascript.JSException class 699
netscape.javascript.JSObject class 695
netscape.javascript.Plugin class 701
new operator 69
news: (URL语法) 346
next method
of Cursor objects 597, 609
of ResultSet objects 597, 609
next property 364
Number object 154
numbers
cosine of 146
greater of two 148
identifying 668
Number object 154
obtaining integer 145
parsing from strings 681
square root 152

O

Objects
Blob 610
objects 141-??
creating new types 69
establishing default 90
focus 319, 392, 401, 421, 424, 428, 435, 444, 463
specifying names in event handlers 321
onAbort event handler 499
onLoad event handler 515
onMouseOut event handler 519
onMouseOver event handler 520
onReset event handler 523
onSelect event handler 525
onSubmit event handler 526
onUnload event handler 527
open method 649
document object 242
window object 328
opener property 307
operators
arithmetic 62-63
assignment 60
bitwise 63-65
comparison 61
logical 66
special 68
string 67
outParamCount method
of StoredProc objects 602
outParameters method
of StoredProc objects 602, 604
output buffer
flushing 667

P

packages 695-703
parent property 310
parse method 120
parseFloat function 627, 681
parseInt function 627, 682
Password object 403
default value 388, 397, 405
PATH_INFO CGI variable 687
PATH_TRANSLATED CGI variable 687
pathname property 257, 353
PI property 140
Plugin class 701
Plugin constructor (LiveConnect) 703
Plugin object 486
plug-ins
defined 486
determining installed 487
port property 257, 354, 634
POSITIVE_INFINITY property 158
pow method 150
previous property 364
printing generated HTML 247
project object 629
prompt method 333
Properties
of Cursor objects 590
properties 141-??
preserving client values 669
protocol property 258, 355
request object 624
server object 635
prototype property 99, 112, 115, 158, 162, 173, 273, 533, 555, 571, 592, 601, 606, 642, 663

Q

QUERY_STRING CGI variable 687

R

radio buttons
clicking programmatically 428, 435, 445
default selection state 441
Radio object 437
Radio object 437
random method 150
read method 651
readByte method 652
readln method 653
redirect function 684
referrer property 238
refresh method 479
registerCFunction function 685
reload method 358
REMOTE_ADDR CGI variable 687
REMOTE_HOST CGI variable 687
REMOTE_USER CGI variable 687
removeMember method (LiveConnect) 698
replace method 359
request
changing 668
request object 618
REQUEST_METHOD CGI variable 687
reset buttons
clicking programmatically 428, 435, 445
Reset object 429
reset event 523
reset method 380
Reset object 429
resizeBy method 334
resizeTo method 335
response headers
manipulating 667, 670
ResultSet objects 604-??
next method 597, 609
return statement 87
returnValue method
of StoredProc objects 603, 604
reverse method 102
right shift operators 65
round method 151

S

scope
of connection objects 554
SCRIPT_NAME CGI variable 687
scroll method 336
scrollBy method 336
scrollTo method 337
search property 259, 356
security
closing windows 321
select event 525
Select object 453
SELECT tag 668
selectedIndex property 461
selection lists
adding options 465
changing option text 465
default selection state 467
deleting options 460
number of options 98, 173, 363, 377
option text 468
Select object 453
self property 312
server
global data for 632
server JavaScript 50
server object 632
SERVER_NAME CGI variable 688
SERVER_PORT CGI variable 688
SERVER_PROTOCOL CGI variable 688
SERVER_URL CGI variable 688
session key 687
setDate method 121
setHours method 121
setMember method (LiveConnect) 698
setMinutes method 122
setMonth method 122
setPosition method 654
setSeconds method 123
setSlot method (LiveConnect) 699
setTime method 123
setTimeout method 340
setYear method 124
sin method 152
small method 191
sort method 106
special operators 68
typeof 72
void 73
split method 192
SQL xliii
sqrt method 152
SQRT1_2 property 140
SQRT2 property 141
square roots 152
src property 273, 285
ssjs_getCGIVariable function 687
ssjs_getClientID function 688
statements 75-91
syntax conventions 75
status property 313
stop method 342
StoredProc objects ??-603
outParamCount method 602
outParameters method 602, 604
returnValue method 603, 604
storedProcArgs method
of DbPool objects 551, 567
strike method 195
String object 170
string operators 67
strings
blinking 175
bold 176
character position within 171, 177, 183
converting from bytes 642
converting from date 125
converting to floating point 681
creating from arrays 100
defining 170
fontsize of 175
length of 98, 173, 363, 377
lowercase 172, 200
parsing 668
splitting into arrays 192
String object 170
stringToByte method 655
sub method 195
submit buttons
clicking programmatically 428, 435, 445
defining 423
Submit object 423
submit event 526
submit method 381
Submit object 423
substring method 197
suffixes property 485
sup method 199
syntax conventions 75

T

tan method 153
target property 259, 379
TCP port 688
Text object 386
default value 388, 397, 405
Textarea object 394
default value 388, 397, 405
this keyword 72
this.form 383, 388, 397, 405, 412, 417, 425, 432, 442, 450, 458
timeouts
canceling 320
times
Date object 113
defining 113
minutes 117
title property 239
toGMTString method 124
toLocaleString method 125
toLowerCase method 200
top property 285, 315
toString method 109, 112, 135, 159, 164, 552, 568, 587
built-in 164
user-defined 165
toString method (LiveConnect) 699
toUpperCase method 200
Trace facility 673
transactions
committing 537, 557
overview 532
rolling back 537, 557
scope of 532, 533, 535, 548, 572, 573, 584
trigonometric methods
cos 146
typeof operator 72

U

unary negation 63
unescape function 691
unique identifier 668, 688
unload event 527
updateRow method
of Cursor objects 598
URL
redirecting to 668
URLs 688
adding information to 667
anchor name in 254
conventions used xlv
current 344
escaping characters in 667
examples of common 346
history list 361
next 325
syntax of 346
user interaction
applets 276
area objects 277
checkboxes 446
Confirm dialog box 322
image objects 277
link objects 277
Prompt dialog box 333
submit buttons 423
userAgent property 479
UTC method 126

V

valueOf method 167
var statement 88
variables
declaring 88
initializing 88
syntax for declaring 88
view-source: (URL语法) 346
vlinkColor property 240
void function 251, 347
void operator 73
vspace property 275

W

while loops
continuation of 78
syntax of 89
termination of 77
while statement 89
width property 275
window object 294
windows
closed 301
closing 321
name of 307, 378, 390, 399, 450
top 285, 315
window object 294
with statement 90
write function 693
and flush 677
write method 246
generated HTML 247
writeByte method 657
writeln method 249, 658

【上一章】 【目录】 【这是索引】


JavaScript语言参考手册_进程管理服务

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

第十一章
进程管理服务

本章包含了与管理进程相关的服务器端对象，包括 request、client、project、server 和 Lock 。

表 11.1 本章用到的对象总览。

表 11.1 进程管理服务
对象 | 描述
client | 封装了关于客户/应用程序对的信息，允许信息持续的时间长于单个的 HTTP 请求。
Lock | 提供了在请求、客户和应用程序之间共享数据的功能。
project | 封装了关于持续到该应用程序在服务器上停止的应用程序的信息。
request | 封装了关于单个的 HTTP 请求的信息。
server | 封装了关于持续到服务器停止的服务器的全局信息。

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


JavaScript语言参考手册_进程管理服务

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

request

 Contains data specific to the current client request.

服务器端对象 |
实现版本 | LiveWire 1.0

创建源

The JavaScript runtime engine on the server automatically creates a request object for each client request.

描述

The JavaScript runtime engine on the server creates a request object each time the client makes a request of the server. The runtime engine destroys the request object after the server responds to the request, typically by providing the requested page.

The properties listed below are read-only properties that are initialized automatically when a request object is created. In addition to these predefined properties, you can create custom properties to store application-specific data about the current request.

属性概览

agent | Provides name and version information about the client software.
imageX | The horizontal position of the mouse pointer when the user clicked the mouse over an image map.
imageY | The vertical position of the mouse pointer when the user clicked the mouse over an image map.
inputName | Represents an input element on an HTML form. (There is not a 属性 whose name is inputName. Rather, each instance of request has properties named after each input element.)
ip | Provides the IP address of the client.
方法 | Provides the HTTP 方法 associated with the request.
protocol | Provides the HTTP protocol level supported by the client's software.

方法概览

无。

示例

示例 1. This example displays the values of the predefined properties of the request object. In this example, an HTML form is defined as follows:

<FORM METHOD="post" NAME="idForm" ACTION="hello.html">
<P>Last name:
<INPUT TYPE="text" NAME="lastName" SIZE="20">
<BR>First name:
<INPUT TYPE="text" NAME="firstName" SIZE="20">
</FORM> The following code displays the values of the request object properties that are created when the form is submitted:

agent = <SERVER>write(request.agent)</SERVER><BR>
ip = <SERVER>write(request.ip)</SERVER><BR>
method = <SERVER>write(request.method)</SERVER><BR>
protocol = <SERVER>write(request.protocol)</SERVER><BR>
lastName = <SERVER>write(request.lastName)</SERVER><BR>
firstName = <SERVER>write(request.firstName)</SERVER>
When it executes, this code displays information similar to the following:

agent = "Mozilla/2.0 (WinNT;I)"
ip = "165.327.114.147"
method = "GET"
protocol = "HTTP/1.0"
lastName = "Schaefer"
firstName = "Jesse"
示例 2. The following example creates the requestDate property and initializes it with the current date and time:

request.requestDate = new Date() 示例 3. When a user clicks the following link, the info.html page is loaded, request.accessedFrom is created and initialized to "hello.html", and request.formId is created and initialized to "047".

Click here for
<A HREF="info.html?accessedFrom=hello.html&formId=047">
additional information</A>.

参看

client, project, server

属性

Custom属性

 You can create a property for the request object by assigning it a name and a value. For example, you can create a request property to store the date and time that a request is received so you can enter the date into the page content.

You can also create request object properties by encoding them in a URL. When a user navigates to the URL by clicking its link, the properties are created and instantiated to values that you specify. The properties are valid on the destination page.

Use the following语法 to encode a request property in a URL:

<A HREF="URL?propertyName=value&propertyName=value..."> where:

  • URL is the URL the page that will get the new request properties.

  • propertyName is the name of the property you are creating.

  • value is the initial value of the new property.
Use escape to encode non-alphanumeric values in the URL string.

You can also create custom properties for the request object.

agent

Provides name and version information about the client software.

属性源 | request
只读 |
实现版本 | LiveWire 1.0

描述

The agent property identifies the client software. Use this information to conditionally employ certain features in an application.

The value of the agent property is the same as the value of the userAgent property of the client-side navigator object. The agent property specifies client information in the following format:

codeName/releaseNumber (platform; country; platformIdentifier)

The values contained in this format are the following:

  • codeName is the code name of the client. For example, "Mozilla" specifies Navigator.

  • releaseNumber is the version number of the client. For example, "2.0b4" specifies Navigator 2.0, beta 4.

  • platform is the platform upon which the client is running. For example, "Win16" specifies a 16-bit version of Windows, such as Windows 3.11.

  • country is either "I" for the international release or "U" for the domestic U.S. release. The domestic release has a stronger encryption feature than the international release.

  • platformIdentifier is an optional identifier that further specifies the platform. For example, in Navigator 1.1, platform is "windows" and platformIdentifier is "32bit". In Navigator 2.0, both pieces of information are contained in the platform designation. For example, in Navigator 2.0, the previous platform is expressed as "WinNT".

示例

 The following example displays client information for Navigator 2.0 on Windows NT:

write(request.agent)
\\Displays "Mozilla/2.0 (WinNT;I)" The following example evaluates the request.agent property and runs the oldBrowser procedure for clients other than Navigator 2.0. If the browser is Navigator 2.0, the currentBrowser function executes.

<SERVER>
var agentVar=request.agent
if (agentVar.indexOf("2.0")==-1)
oldBrowser()
else
currentBrowser()
</SERVER>

参看

request.ip, request.method, request.protocol

imageX

The horizontal position of the mouse pointer when the user clicked the mouse over an image map.

属性源 | request
只读 |
实现版本 | LiveWire 1.0

描述

The ISMAP attribute of the IMG tag indicates a server-based image map. When the user clicks the mouse with the pointer over an image map, the horizontal and vertical position of the pointer are returned to the server.

The imageX property returns the horizontal position of the mouse cursor when the user clicks on an image map.

示例

Suppose you define the following image map:

<A HREF="mapchoice.html">
<IMG SRC="images\map.gif" WIDTH=599 WIDTH=424 BORDER=0 ISMAP
ALT="SANTA CRUZ COUNTY">
</A>
Note the ISMAP attribute that makes the image a clickable map. When the user clicks the mouse on the image, the page mapchoice.html will have properties request.imageX and request.imageY based on the mouse cursor position where the user clicked.

参看

request.imageY

imageY

The vertical position of the mouse pointer when the user clicked the mouse over an image map.

属性源 | request
只读 |
实现版本 | LiveWire 1.0

描述

The ISMAP attribute of the IMG tag indicates a server-based image map. When the user clicks the mouse with the pointer over an image map, the horizontal and vertical position of the pointer are returned to the server.

The imageY property returns the vertical position of the mouse cursor when the user clicks on an image map.

示例

See example for imageX.

参看

request.imageX

inputName

Represents an input element on an HTML form.

属性源 | request
只读 |
实现版本 | LiveWire 1.0

描述

Each input element in an HTML form corresponds to a property of the request object. The name of each of these properties is the name of the field on the associated form. inputName is a variable that represents the value of the name property of an input field on a submitted form. By default, the value of the JavaScript name property is the same as the HTML NAME attribute.

示例

The following HTML source creates the request.lastName and the request.firstName properties when idForm is submitted:

<FORM METHOD="post" NAME="idForm" ACTION="hello.html">
<P>Last name:
<INPUT TYPE="text" NAME="lastName" SIZE="20">
<BR>First name:
<INPUT TYPE="text" NAME="firstName" SIZE="20">
</FORM>

ip

Provides the IP address of the client.

属性源 | request
只读 |
实现版本 | LiveWire 1.0

描述

The IP address is a set of four numbers between 0 and 255, for example, 198.217.226.34. You can use the IP address to authorize or record access in certain situations.

示例

In the following example, the indexOf method evaluates request.ip to determine if it begins with the string "198.217.226". The if statement executes a different function depending on the result of the indexOf method.

<SERVER>
var ipAddress=request.ip
if (ipAddress.indexOf("198.217.226.")==-1)
limitedAccess()
else
fullAccess()
</SERVER>

参看

request.agent, request.method, request.protocol

method

Provides the HTTP method associated with the request.

属性源 | request
只读 |
实现版本 | LiveWire 1.0

描述

The value of the method property is the same as the value of the method property of the client-side Form object. That is, method reflects the METHOD attribute of the FORM tag. For HTTP 1.0, the method property evaluates to either "get" or "post". Use the method property to determine the proper response to a request.

示例

The following example executes the postResponse function if the method property evaluates to "post". If method evaluates to anything else, it executes the getResponse function.

<SERVER>
if (request.method=="post")
postResponse()
else
getResponse()
</SERVER>

参看

request.agent, request.ip, request.protocol

protocol

Provides the HTTP protocol level supported by the client's software.

属性源 | request
只读 |
实现版本 | LiveWire 1.0

描述

For HTTP 1.0, the protocol value is "HTTP/1.0". Use the protocol property to determine the proper response to a request.

示例

In the following example, the currentProtocol function executes if request.protocol evaluates to "HTTP/1.0".

<SERVER>
if (request.protocol=="HTTP/1.0"
currentProtocol()
else
unknownProtocol()
</SERVER>

参看

request.agent, request.ip, request.method


JavaScript语言参考手册_进程管理服务

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

client

 Contains data specific to an individual client.

服务器端对象 |
实现版本 | LiveWire 1.0

创建源

The JavaScript runtime engine on the server automatically creates a client object for each client/application pair.

描述

The JavaScript runtime engine on the server constructs a client object for every client/application pair. A browser client connected to one application has a different client object than the same browser client connected to a different application. The runtime engine constructs a new client object each time a user accesses an application; there can be hundreds or thousands of client objects active at the same time.

You cannot use the client object on your application's initial page. This page is run when the application is started on the server. At this time, there is not a client request, so there is no available client object.

The runtime engine constructs and destroys the client object for each client request. However, at the end of a request, the runtime engine saves the names and values of the client object's properties so that when the same user returns to the application with a subsequent request, the runtime engine can construct a new client object with the saved data. Thus, conceptually you can think of the client object as remaining for the duration of a client's session with the application. There are several different ways to maintain client property values; for more information, see Writing Server-Side JavaScript Applications.

All requests by one client use the same client object, as long as those requests occur within the lifetime of that client object. By default, a client object persists until the associated client has been inactive for 10 minutes. You can use the expiration method to change this default lifetime or the destroy method to explicitly destroy the client object.

Use the client object to maintain data that is specific to an individual client. Although many clients can access an application simultaneously, the individual client objects keep their data separate. Each client object can track the progress of an individual client across multiple requests to the same application.

方法概览

destroy | Destroys a client object.
expiration | Specifies the duration of a client object.

示例

示例 1. This example dynamically assigns a customer ID number that is used for the lifetime of an application session. The assignId function creates an ID based on the user's IP address, and the customerId property saves the ID.

<SERVER>client.customerId = assignId(request.ip)</SERVER> See also the示例 for the project object for a way to sequentially assign a customer ID.

示例 2. This example creates a customerId property to store a customer ID that a user enters into a form. The form is defined as follows:

<FORM NAME="getCustomerInfo" METHOD="post">
<P>Enter your customer ID:
<INPUT TYPE="text" NAME="customerNumber">
</FORM> The following code assigns the value entered in the customerNumber field from the temporary request.clientNumber to the more permanent client.customerId:

<SERVER>client.customerId=request.customerNumber</SERVER>

参看

project, request, server

属性

The client object has no predefined properties. You create custom properties to contain any client-specific data that is required by an application. The runtime engine does not save client objects that have no property values.

You can create a property for the client object by assigning it a name and a value. For example, you can create a client property to store a customer ID at the beginning of an application so a user does not have to enter it with each request.

Because of the techniques used to maintain client properties across multiple client requests, there is one major restriction on client property values. The JavaScript runtime engine on the server converts the values of all of the client object's properties to strings.

The runtime engine cannot convert an object to a string. For this reason, you cannot assign an object as the value of a client property. If a client property value represents another data type, such as a number, you must convert the value from a string before using it. The core JavaScript parseInt and parseFloat functions are useful for converting to integer and floating point values.

方法

destroy

 Destroys a client object.

方法源 | client
实现版本 | LiveWire 1.0

语法

destroy()

描述

 The destroy method explicitly destroys the client object that issues it and removes all properties from the client object. If you do not explicitly issue a destroy method, the JavaScript runtime engine on the server automatically destroys the client object when its lifetime expires. The expiration method sets the lifetime of a client object; by default, the lifetime is 10 minutes.

If you are using client-cookies to maintain the client object, destroy eliminates all client property values, but it does not affect what is stored in Navigator cookie file. Use expiration with an argument of 0 seconds to remove all client properties stored in the cookie file.

When using client URL encoding to maintain the client object, destroy removes all client properties after the method call. However, any links in a page before the call to destroy retain properties in their URLs. Therefore, you should generally call destroy either at the top or bottom of the page when using client URL maintenance.

示例

The following method destroys the client object that calls it:

<server>client.destroy()</server>

参看

client.expiration

expiration

Specifies the duration of a client object.

方法源 | client
实现版本 | LiveWire 1.0

语法

expiration(seconds)

参数

seconds An integer representing the number of seconds of client inactivity before the client object expires.

描述

By default, the JavaScript runtime engine on the server destroys the client object after the client has been inactive for 10 minutes. This default lifetime lets the runtime engine clean up client objects that are no longer necessary.

Use the expiration method to explicitly control the expiration of a client object, making it longer or shorter than the default. You must use expiration in each page of an application for which you want a client expiration other than the default. Any page that does not specify an expiration will use the default of 10 minutes.

Client expiration does not apply if using client URL encoding to maintain the client object. In this case, client properties are stored solely in URLs on HTML pages. The runtime engine cannot remove those properties.

示例

The following example extends the amount of client inactivity before expiration to 1 hour. This code is issued when an application is first launched.

<SERVER>client.expiration(3600)</SERVER>

参看

client.destroy


JavaScript语言参考手册_进程管理服务

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

project

 Contains data for an entire application.

服务器端对象 |
实现版本 | LiveWire 1.0

创建源

The JavaScript runtime engine on the server automatically creates a project object for each application running on the server.

描述

The JavaScript runtime engine on the server creates a project object when an application starts and destroys the project object when the application or server stops. The typical project object lifetime is days or weeks.

Each client accessing the same application shares the same project object. Use the project object to maintain global data for an entire application. Many clients can access an application simultaneously, and the project object lets these clients share information.

The runtime engine creates a set of project objects for each distinct Netscape HTTPD process running on the server. Because several server HTTPD processes may be running on different port numbers, the runtime engine creates a set of project objects for each process.

You can lock the project object to ensure that different clients do not change its properties simultaneously. When one client locks the project object, other clients must wait before they can lock it. See Lock for more information about locking the project object.

方法概览

lock | Obtains the lock.
unlock | Releases the lock.

示例

示例 1. This example creates the lastID property and assigns a value to it by incrementing an existing value.

project.lastID = 1 + parseInt(project.lastID, 10) 示例 2. This example increments the value of the lastID property and uses it to assign a value to the customerID property.

project.lock()
project.lastID = 1 + parseInt(project.lastID, 10);
client.customerID = project.lastID;
project.unlock();
In the previous example, notice that the project object is locked while the customerID property is assigned, so no other client can attempt to change the lastID property at the same time.

参看

client, request, server

属性

The project object has no predefined properties. You create custom properties to contain project-specific data that is required by an application.

You can create a property for the project object by assigning it a name and a value. For example, you can create a project object property to keep track of the next available Customer ID. Any client that accesses the application without a Customer ID is sequentially assigned one, and the value of the ID is incremented for each initial access.

方法

lock

 Obtains the lock. If another thread has the lock, this method waits until it can get the lock.

方法源 | project
实现版本 | LiveWire 1.0

语法

lock()

参数

 无。

返回

Nothing.

描述

You can obtain a lock for an object to ensure that different clients do not access a critical section of code simultaneously. When an application locks an object, other client requests must wait before they can lock the object.

Note that this mechanism requires voluntary compliance by asking for the lock in the first place.

参看

Lock, project.unlock

unlock

Releases the lock.

方法源 | project
实现版本 | LiveWire 1.0

语法

unlock()

参数

 无。

返回

False if it fails; otherwise, true. Failure indicates an internal JavaScript error or that you attempted to unlock a lock that you don't own.

描述

If you unlock a lock that is unlocked, the resulting behavior is undefined.

参看

Lock, project.lock


JavaScript语言参考手册_进程管理服务

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

server

 Contains global data for the entire server.

服务器端对象 |
实现版本 | LiveWire 1.0

创建源

The JavaScript runtime engine on the server automatically creates a single server object to store information common to all JavaScript applications running on the web server.

描述

The JavaScript runtime engine on the server creates a server object when the server starts and destroys it when the server stops. Every application on a server shares the same server object. Use the server object to maintain global data for the entire server. Many applications can run on a server simultaneously, and the server object lets them share information.

The runtime engine creates a server object for each distinct Netscape HTTPD process running on the server.

The properties listed below are read-only properties that are initialized automatically when a server object is created. These properties provide information about the server process. In addition to these predefined properties, you can create custom properties.

You can lock the server object to ensure that different applications do not change its properties simultaneously. When one application locks the server object, other applications must wait before they can lock it.

属性概览

host | String specifying the server name, subdomain, and domain name.
hostname | String containing the full hostname of the server, including the server name, subdomain, domain, and port number.
port | String indicating the port number used for the server.
protocol | String indicating the communication protocol used by the server.

方法概览

lock | Obtains the lock.
unlock | Releases the lock.

示例

The following example displays the values of the predefined server object properties:

<P>server.host = <SERVER>write(server.host);</SERVER>
<BR>server.hostname = <SERVER>write(server.hostname);</SERVER>
<BR>server.protocol = <SERVER>write(server.protocol);</SERVER>
<BR>server.port = <SERVER>write(server.port);</SERVER>
The preceding code displays information such as the following:

server.host = www.myWorld.com
server.hostname = www.myWorld.com:85
server.protocol = http:
server.port = 85

参看

client, project, request

属性

host

 A string specifying the server name, subdomain, and domain name.

属性源 | server
只读 |
实现版本 | LiveWire 1.0

描述

The host property specifies a portion of a URL. The host property is a substring of the hostname property. The hostname property is the concatenation of the host and port properties, separated by a colon. When the port property is 80 (the default), the host property is the same as the hostname property.

See Section 3.1 of RFC 1738 (http://www.cis.ohio-state.edu/htbin/rfc/rfc1738.html) for complete information about the hostname and port.

参看

server.hostname, server.port, server.protocol

hostname

A string containing the full hostname of the server, including the server name, subdomain, domain, and port number.

属性源 | server
只读 |
实现版本 | LiveWire 1.0

描述

The hostname property specifies a portion of a URL. The hostname property is the concatenation of the host and port properties, separated by a colon. When the port property is 80 (the default), the host property is the same as the hostname property.

See Section 3.1 of RFC 1738 (http://www.cis.ohio-state.edu/htbin/rfc/rfc1738.html) for complete information about the hostname and port.

参看

server.host, server.port, server.protocol

port

A string indicating the port number used for the server.

属性源 | server
只读 |
实现版本 | LiveWire 1.0

描述

The port property specifies a portion of the URL. The port property is a substring of the hostname property. The hostname property is the concatenation of the host and port properties, separated by a colon.

The default value of the port property is 80. When the port property is set to the default, the values of the host and hostname properties are the same.

See Section 3.1 of RFC 1738 (http://www.cis.ohio-state.edu/htbin/rfc/rfc1738.html) for complete information about the port.

参看

server.host, server.hostname, server.protocol

protocol

A string indicating the communication protocol used by the server.

属性源 | server
只读 |
实现版本 | LiveWire 1.0

描述

The protocol property specifies the beginning of the URL, up to and including the first colon. The protocol indicates the access method of the URL. For example, a protocol of "http:" specifies HyperText Transfer Protocol.

The protocol property represents the scheme name of the URL. See Section 2.1 of RFC 1738 (http://www.cis.ohio-state.edu/htbin/rfc/rfc1738.html) for complete information about the protocol.

参看

server.host, server.hostname, server.port

方法

lock

 Obtains the lock. If another thread has the lock, this method waits until it can get the lock.

方法源 | server
实现版本 | LiveWire 1.0

语法

lock()

参数

 无

返回

Nothing.

描述

You can obtain a lock for an object to ensure that different clients do not access a critical section of code simultaneously. When an application locks an object, other client requests must wait before they can lock the object.

Note that this mechanism requires voluntary compliance by asking for the lock in the first place.

参看

Lock, server.lock

unlock

Releases the lock.

方法源 | server
实现版本 | LiveWire 1.0

语法

unlock()

参数

 无。

返回

False if it fails; otherwise, true. Failure indicates an internal JavaScript error or that you attempted to unlock a lock that you don't own.

描述

If you unlock a lock that is unlocked, the resulting behavior is undefined.

参看

Lock, server.unlock


JavaScript语言参考手册_进程管理服务

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

Lock

 Provides a way to lock a critical section of code.

服务器端对象 |
实现版本 | Netscape Server 3.0

创建源

The Lock constructor:

Lock();

参数

无。

Failure to construct a new Lock object indicates an internal JavaScript error, such as out of memory.

方法概览

lock | Obtains the lock.
isValid | Verifies that this Lock object was properly constructed.
unlock | Releases the lock.

参看

project.lock, project.unlock, server.lock, server.unlock

方法

语法

lock

 Obtains the lock. If someone else has the lock, this method blocks until it can get the lock, the specified timeout period has elapsed, or an error occurs.

方法源 | Lock
实现版本 | Netscape Server 3.0

语法

lock(timeout)

参数

timeout An integer indicating the number of seconds to wait for the lock. If 0, there is no timeout; that is, the 方法 waits indefinitely to obtain the lock. The default value is 0, so if you do not specify a value, the 方法 waits indefinitely.

返回

True if it succeeds in obtaining the lock within the specified timeout. False if it did not obtain the lock.

描述

You can obtain a lock for an object to ensure that different clients do not access a critical section of code simultaneously. When an application locks an object, other client requests must wait before they can lock the object.

Note that this mechanism requires voluntary compliance by asking for the lock in the first place.

参看

Lock.unlock, Lock.isValid, project.lock, server.lock

isValid

Verifies that this Lock object was properly constructed.

方法源 | Lock
实现版本 | Netscape Server 3.0

语法

isValid()

参数

 无。

返回

True, if this object was properly constructed; otherwise, false.

描述

It is very rare that your Lock object would not be properly constructed. This happens only if the runtime engine runs out of system resources while creating the object.

示例

This code creates a Lock object and verifies that nothing went wrong creating it:

// construct a new Lock and save in project
project.ordersLock = new Lock();
if (! project.ordersLock.isValid()) {
// Unable to create a Lock. Redirect to error page
...
}

参看

Lock.lock, Lock.unlock

unlock

Releases the lock.

方法源 | Lock
实现版本 | Netscape Server 3.0

语法

unlock()

参数

 无。

返回

False if it fails; otherwise, true. Failure indicates an internal JavaScript error or that you attempted to unlock a lock that you don't own.

描述

If you unlock a lock that is unlocked, the resulting behavior is undefined.

参看

Lock.lock, Lock.isValid, project.unlock, server.unlock

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


JavaScript语言参考手册_语句

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

第三章
语句

本章描述了所有的 JavaScript 语句。JavaScript 语句由关键字和相应的语法构成。一个单独的语句可以写在多行上。如果用分号隔开的话，多个语句也可出现在一行上。

语法凡例：语法语句中的所有关键字都是粗体。而斜体字代表用户自定义的名称或语句。任何出现了方括号“[]”内的内容都是可选的。{语句组}代表一个语句块，可由单个语句或多个语句组成，但外面要有花括号“{}”。

表 3.1 列出了 JavaScript 中可用的语句。

表 3.1 JavaScript 语句
break | 该语句用于结束当前的 while 或 for 循环，并将程序控制权交给循环后面的语句。
comment | 作者书写的文字，用于解释脚本的作用。注释将被解释器忽略。
continue | 该语句用于中止 while 或 for 循环中一块语句的执行，并且直接执行下一次循环。
delete | 删除一个对象的属性或数组中的一个元素。
do...while | 一直执行其中包含的语句，直到测试条件为假。内含语句至少被执行一次。
export | 允许一个签字的脚本向其它签字或未签字的脚本提供属性、函数和对象。
for | 该语句用于创建由三个可选表达式组成的循环，用分号隔开，外面包有圆括号，后面跟着一块将要在循环中执行的语句。
for...in | 该语句用于遍历一个对象的所有属性的特定变量。对于每个属性，JavaScript 都将执行特定的语句。
function | 该语句用于声明一个带有指定参数的 JavaScript 函数。可以接受的参数包括字符串、数值和对象。
if...else | 该语句用于在指定条件为真的情况下执行一组语句。如果条件为假的话，则可执行另外一组语句。
import | 允许脚本引入其它签字脚本已经导出的属性、函数和对象。
labeled | 提供一个表示符，和 break 或 continue 一起使用可标明程序应该继续执行的流程。
return | 该语句用于指定函数的返回值。
switch | 允许程序计算一个表达式，并试图将表达式的值与某个 case 标签匹配。
var | 该语句用于声明变量，可选赋初值。
while | 该语句用于创建一个计算某表达式的循环，如果该表达式位真的话，则持续执行一块语句。
with | 该语句用于位一组语句建立缺省的对象。

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


JavaScript语言参考手册_语句

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

break

 Terminates the current while or for loop and transfers program control to the statement following the terminated loop.

实现版本 Navigator 2.0, LiveWire 1.0

语法

break
break label

Argument

label Identifier associated with the label of the statement.

描述

The break statement can now include an optional label that allows the program to break out of a labeled statement. This type of break must be in a statement identified by the label used by break.

The statements in a labeled statement can be of any type.

示例

The following function has a break statement that terminates the while loop when e is 3, and then returns the value 3 * x.

function testBreak(x) {
var i = 0
while (i < 6) {
if (i == 3)
break
i++
}
return i*x
}
In the following example, a statement labeled checkiandj contains a statement labeled checkj. If break is encountered, the program breaks out of the checkj statement and continues with the remainder of the checkiandj statement. If break had a label of checkiandj, the program would break out of the checkiandj statement and continue at the statement following checkiandj.

checkiandj :
if (4==i) {
document.write("You've entered " + i + ".<BR>");
checkj :
if (2==j) {
document.write("You've entered " + j + ".<BR>");
break checkj;
document.write("The sum is " + (i+j) + ".<BR>");
}
document.write(i + "-" + j + "=" + (i-j) + ".<BR>");
}

参看

labeled, switch


JavaScript语言参考手册_语句

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

comment

 由作者所写，用于解释脚本的所用。注释将被解释器忽略。

实现版本 Navigator 2.0, LiveWire 1.0

语法

// 注释文本
/* 多行注释文本 */

描述

JavaScript 支持 Java 风格的注释：

  • 由双斜线起始的单行注释。

  • 跨多行的注释由 /* 起始，*/ 结束。

示例

 // 这是一个单行注释。
/* 这是一个多行注释。它可以为任意长度，你可以将它放在任何
你想要它出现的地方。*/


JavaScript语言参考手册_语句

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

continue

 Terminates execution of the block of statements in a while or for loop, and continues execution of the loop with the next iteration.

实现版本 Navigator 2.0, LiveWire 1.0

语法

continue
continue label

Argument

label Identifier associated with the label of the statement.

描述

In contrast to the break statement, continue does not terminate the execution of the loop entirely: instead,

  • In a while loop, it jumps back to the condition.

  • In a for loop, it jumps to the update expression.
The continue statement can now include an optional label that allows the program to terminate execution of a labeled statement and continue to the specified labeled statement. This type of continue must be in a looping statement identified by the label used by continue.

示例

The following example shows a while loop that has a continue statement that executes when the value of i is 3. Thus, n takes on the values 1, 3, 7, and 12.

i = 0
n = 0
while (i < 5) {
i++
if (i == 3)
continue
n += i
}
In the following example, a statement labeled checkiandj contains a statement labeled checkj. If continue is encountered, the program continues at the top of the checkj statement. Each time continue is encountered, checkj reiterates until its condition returns false. When false is returned, the remainder of the checkiandj statement is completed. checkiandj reiterates until its condition returns false. When false is returned, the program continues at the statement following checkiandj.

If continue had a label of checkiandj, the program would continue at the top of the checkiandj statement.

checkiandj :
while (i<4) {
document.write(i + "<BR>");
i+=1;
   checkj :
while (j>4) {
document.write(j + "<BR>");
j-=1;
if ((j%2)==0)
continue checkj;
document.write(j + " is odd.<BR>");
}
document.write("i = " + i + "<br>");
document.write("j = " + j + "<br>");
}

参看

labeled


JavaScript语言参考手册_语句

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

delete

 删除对象的属性，或者删除数组中的指定元素。

实现版本 Navigator 4.0, Netscape Server 3.0

语法

delete objectName.property
delete objectName[index]
delete property

参数

objectName | 要删除属性或元素的对象。
属性 | 要删除的属性。
index | 要删除的数组元素的序号。

描述

如果 delete 操作符成功的话，它就会将元素的属性设定为未定义；操作符总是返回未定义。

你只能使用 delete 操作符删除对象属性或数组元素。你不能使用该操作符删除对象或变量。因此，你就只能在 with 语句中使用第三种格式，以便删除对象的属性。


JavaScript语言参考手册_语句

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

do...while

执行指定语句，直到测试条件为假。语句至少被执行一次。

实现版本 Navigator 4.0, Netscape Server 3.0

语法

do
statement
while (condition);

参数

statement | 该语句块至少被执行一次，并且会在每次条件计算为真的时候重新执行。
condition | 在每次循环完成之后计算该条件。如果计算的结果是真，那么将会重新执行循环体中的语句。如果条件计算为假，将会把控制权交给 do while 后面的语句。

示例

在下面的例子中，do 循环将会被至少执行一次，并且会被重复执行直到 i 不再小于 5。

do {
i+=1
document.write(i);
while (i<5);


JavaScript语言参考手册_语句

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

export

 允许标明的脚本向其它标明或未标明的脚本提供属性、函数和对象。

实现版本 Navigator 4.0, Netscape Server 3.0

语法

export name1, name2, ..., nameN
export *

参数

nameN | 列出将要被导出的属性、函数和对象。
* | 导出脚本中所有的属性、函数和对象。

描述

通常情况下标明脚本中的信息仅对象同主体标明的脚本可用。通过导出属性、函数或对象，标明脚本将使得信息对于任何脚本(标明或未标明的)都可用。接收脚本使用对应的 import 语句访问信息。

参看

import


JavaScript语言参考手册_语句

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

for

 创建一个由三个放在括号内以分号分隔的可选表达式组成的循环，后面跟着一块语句作为循环体。

实现版本 Navigator 2.0, LiveWire 1.0

语法

for ([initial-expression;] [condition;] [increment-expression]) {
statements
}

参数

initial-expression | 语句或变量声明。典型情况下用于初始化计数器变量。该表达式可选用 var 关键字声明新变量。
condition | 在每次执行循环的时候计算该表达式。如果该表达式计算为真，就执行 statements 中的语句。该条件测试是可选的。如果缺省的话，那么条件将永远计算为真。此时除非你在循环体内使用 break 语句，否则不能终止循环。
increment-expression | 通常用于更新或自增计数器变量。
statements | 一块只要条件计算为真的时候就执行的语句。这里可以是单个语句或多个语句。尽管语法没有要求，但是建议将这些语句缩进书写。

示例

下列语句开始声明了一个变量 i 并将其初始化为 0。它检查 i 是否小于 9，执行两个成功的语句，并且让 i 在每个循环后自增 1。

for (var i = 0; i < 9; i++) {
n += i
myfunc(n)
}


JavaScript语言参考手册_语句

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

for...in

 对一个对象的所有属性重复赋给一个特定变量，JavaScript 会对每个不同的属性都执行特定的语句。

实现版本 Navigator 2.0, LiveWire 1.0

语法

for (variable in object) {
statements}

参数

variable | 要遍历所有属性的变量。
object | 要遍历属性的对象。
statements | 指定要对每个属性执行的语句。

示例

下面的函数需要一个对象和该对象名称两个参数。然后它会变量该对象的所有属性并返回一个字符串，其中列出了属性名称及属性值。

function dump_props(obj, objName) {
var result = ""
for (var i in obj) {
result += objName + "." + i + " = " + obj[i] + "<BR>"
}
result += "<HR>"
return result
}


JavaScript语言参考手册_语句

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

function

 声明一个带有指定参数的 JavaScript 函数。可以接受的参数包括字符串、数值和对象。

实现版本 Navigator 2.0, LiveWire 1.0

语法

function name([param] [, param] [..., param]) {
statements}

参数

name | 函数名称。
param | 要传送给函数的参数名称。一个函数最多可以有 255 个参数。

描述

要返回值，函数必须有一个指定返回值的 return 语句。你不能在其它语句或其自身中嵌套 function 语句。

所有传递给函数的参数都是值传送的。也就是说，将把值传递给函数，但是如果函数更改了参数的值，那么这个更改将不会影响全局或调用该函数的函数。

除了在此说明的可以定义函数之外，你还可以定义 Function 对象。

示例

//该函数返回销售额的总计，总计是通过传递过来的
//产品 a、b、c 的销售量计算出来的
function calc_sales(units_a, units_b, units_c) {
return units_a*79 + units_b*129 + units_c*699
}


JavaScript语言参考手册_语句

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

if...else

 如果指定条件为真的话执行一组语句。如果条件为假的话，执行另外一组语句。

实现版本 Navigator 2.0, LiveWire 1.0

语法

if (condition) {
statements1}
[else {
statements2}]

参数

condition | 可以是计算值为真或假的 JavaScript 表达式。条件必须用圆括号括起来。如果 condition 的值计算为真的话，就会执行 statements1 中的语句。
statements1 statements2 | 可以是任意的 JavaScript 语句，包括更深层次的嵌套 if 语句。多个语句必需用大括号括起来。

示例

if (cipher_char == from_char) {
result = result + to_char
x++}
else
result = result + clear_char


JavaScript语言参考手册_语句

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

import

 允许脚本从标识的脚本中导入已经导出的属性、函数和对象。

实现版本 Navigator 4.0, Netscape Server 3.0

语法

import objectName.name1, objectName.name2, ..., objectName.nameN
import objectName.*

参数

nameN | 列出了要导入属性、函数和对象的文件。
objectName | 将要接受导入名称的对象的名称。
* | 从导出脚本中导入所有属性、函数和对象。

描述

objectName 参数是将接受导入的名称的对象名称。例如，如果已经导出了 f 和 p，obj 是导入脚本中的一个对象，那么

import obj.f, obj.p 将使得 f 和 p 在导入脚本中可访问，就像是 obj 的属性一样。

通常情况下，标明脚本中的信息仅对象同主体标明的脚本可用。通过导出(使用 export 语句)属性、函数或对象，标明脚本将使得信息对于任何脚本(标明或未标明的)都可用。接收脚本使用对应的 import 语句访问信息。

脚本必须在导入并使用任何导出的属性、函数或对象之前将导出脚本装载到窗口、框架或层中。

参看

export


JavaScript语言参考手册_语句

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

labeled

提供了一个可与 break 或 continue 一起使用的标识符，用于标明程序的执行流程。

实现版本 Navigator 4.0, Netscape Server 3.0

在已标识的语句中，break 或 continue 必须跟在 label 后面；而 label 也必须是包含有 break 或 continue 的已标识语句。

语法

label :
statement

参数

statement 一块语句。break 可在任意已标识语句中使用，continue 可在循环中的标识语句中使用。

示例

要查看使用 break 的标识语句示例，请看 break 。要查看使用 continue 的标识语句示例，请看 continue 。

参看

break, continue


JavaScript语言参考手册_语句

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

return

 指定函数的返回值。

实现版本 Navigator 2.0, LiveWire 1.0

语法

return 表达式

示例

 下列函数返回参数 x 的平方，而 x 是一个数。

function square(x) {
return x * x
}


JavaScript语言参考手册_语句

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

switch

Allows a program to evaluate an expression and attempt to match the expression's value to a case label.

实现版本 Navigator 4.0, Netscape Server 3.0

语法

switch (expression){
case label :
statement;
break;
case label :
statement;
break;
...
default : statement;
}

参数

expression | Value matched against label.
label | Identifier used to match against expression.
statement | Any statement.

描述

If a match is found, the program executes the associated statement.

The program first looks for a label matching the value of expression and then executes the associated statement. If no matching label is found, the program looks for the optional default statement, and if found, executes the associated statement. If no default statement is found, the program continues execution at the statement following the end of switch.

The optional break statement associated with each case label ensures that the program breaks out of switch once the matched statement is executed and continues execution at the statement following switch. If break is omitted, the program continues execution at the next statement in the switch statement.

示例

In the following example, if expression evaluates to "Bananas," the program matches the value with case "Bananas" and executes the associated statement. When break is encountered, the program breaks out of switch and executes the statement following switch. If break were omitted, the statement for case "Cherries" would also be executed.

switch (i) {
case "Oranges" :
document.write("Oranges are $0.59 a pound.<BR>");
break;
case "Apples" :
document.write("Apples are $0.32 a pound.<BR>");
break;
case "Bananas" :
document.write("Bananas are $0.48 a pound.<BR>");
break;
case "Cherries" :
document.write("Cherries are $3.00 a pound.<BR>");
break;
default :
document.write("Sorry, we are out of " + i + ".<BR>");
}
document.write("Is there anything else you'd like?<BR>");


JavaScript语言参考手册_语句

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

var

 声明一个变量，可选赋初值。

实现版本 Navigator 2.0, LiveWire 1.0

语法

var varname [= value] [..., varname [= value] ]

参数

varname | 变量名。可以是任意合法的标识名。
value | 变量初值，可以是任意合法的表达式。

描述

变量的范围仅限于当前函数；而位于函数外声明的变量，范围限于当前应用程序。

在函数外使用变量是可选的；你只需简单的为变量赋值即可声明一个变量。但是声明变量使用变量的较好风格，而且如果在函数中要使用一个与全局变量同名的变量则必须先声明。

示例

var num_hits = 0, cust_no = 0


JavaScript语言参考手册_语句

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

while

 创建这样一个循环，如果计算某表达式为真的话，就执行一块语句。只要指定条件为真的话，循环就将无休止的重复。

实现版本 Navigator 2.0, LiveWire 1.0

语法

while (condition) {
statements
}

参数

condition | 在每次循环开始之前计算该表达式。如果该条件计算为真的话，就执行下面列出的语句。如果条件计算为假的话，就执行 while 语句后面的语句。
statements | 只要条件计算为真的时候就执行这一块语句。尽管语法没有要求，但是建议将这些语句缩进书写。

示例

下面的 while 循环当 n 小于 3 时重复执行循环体。

n = 0
x = 0
while(n < 3) {
n ++
x += n
}
每次循环过程中，n 都会自增一次，然后再加到 x 上。因此，x 和 n 将顺次取得下列值：

  • 第一遍循环完成后：n = 1，x = 1

  • 第二遍循环完成后：n = 2，x = 3

  • 第三遍循环完成后：n = 3，x = 6
在完成第三遍循环之后，由于条件 n < 3 已经不再满足，所以循环终止。


JavaScript语言参考手册_语句

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

with

 为一组语句创建缺省的对象。在这一组语句中，任何不指定对象的属性引用都将被认为是缺省对象的。

实现版本 Navigator 2.0, LiveWire 1.0

语法

with (object){
statements
}

参数

object | 为语句指定要使用的缺省对象，两边必须有圆括号。
statements | 任意语句块。

示例

下面的语句指定了 Math 对象作为缺省对象。在 with 语句里引用的 PI 属性、cos 和 sin 方法就没有指定对象，JavaScript 会假定这些引用都是针对 Math 对象的。

var a, x, y
var r=10
with (Math) {
a = PI * r * r
x = r * cos(PI)
y = r * sin(PI/2)
}

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


JavaScript语言参考手册_表单

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

Text

 A text input field on an HTML form. The user can enter a word, phrase, or series of numbers in a text field.

客户端对象 |
实现版本 | Navigator 2.0 Navigator 3.0: 添加了 type 属性. Navigator 4.0: 添加了 handleEvent 方法。

创建源

The HTML INPUT tag, with "text" as the value of the TYPE attribute. For a given form, the JavaScript runtime engine creates appropriate Text objects and puts these objects in the elements array of the corresponding Form object. You access a Text object by indexing this array. You can index the array either by number or, if supplied, by using the value of the NAME attribute.

To define a Text object, use standard HTML语法 with the addition of JavaScript event handlers.

事件句柄

  • onBlur
  • onChange
  • onFocus
  • onSelect

描述

 A Text object on a form looks as follows:

A Text object is a form element and must be defined within a FORM tag.

Text objects can be updated (redrawn) dynamically by setting the value property (this.value).

属性概览

defaultValue | Reflects the VALUE attribute.
form | Specifies the form containing the Text object.
name | Reflects the NAME attribute.
type | Reflects the TYPE attribute.
value | Reflects the current value of the Text object's field.

方法概览

blur | Removes focus from the object.
focus | Gives focus to the object.
handleEvent | 调用指定事件的控制句柄。
select | Selects the input area of the object.

示例

示例 1. The following example creates a Text object that is 25 characters long. The text field appears immediately to the right of the words "Last name:". The text field is blank when the form loads.

<B>Last name:</B> <INPUT TYPE="text" NAME="last_name" VALUE="" SIZE=25> 示例 2. The following example creates two Text objects on a form. Each object has a default value. The city object has an onFocus event handler that selects all the text in the field when the user tabs to that field. The state object has an onChange event handler that forces the value to uppercase.

<FORM NAME="form1">
<BR><B>City: </B><INPUT TYPE="text" NAME="city" VALUE="Anchorage"
SIZE="20" onFocus="this.select()">
<B>State: </B><INPUT TYPE="text" NAME="state" VALUE="AK" SIZE="2"
onChange="this.value=this.value.toUpperCase()">
</FORM>
See also the示例 for the onBlur, onChange, onFocus, and onSelect.

参看

Text, Form, Password, String, Textarea

属性

defaultValue

 A string indicating the default value of a Text object.

属性源 | Text
实现版本 | Navigator 2.0

安全性

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

描述

The initial value of defaultValue reflects the value of the VALUE attribute. Setting defaultValue programmatically overrides the initial setting.

You can set the defaultValue property at any time. The display of the related object does not update when you set the defaultValue property, only when you set the value property.

示例

The following function evaluates the defaultValue property of objects on the surfCity form and displays the values in the msgWindow window:

function defaultGetter() {
msgWindow=window.open("")
msgWindow.document.write("hidden.defaultValue is " +
document.surfCity.hiddenObj.defaultValue + "<BR>")
msgWindow.document.write("password.defaultValue is " +
document.surfCity.passwordObj.defaultValue + "<BR>")
msgWindow.document.write("text.defaultValue is " +
document.surfCity.textObj.defaultValue + "<BR>")
msgWindow.document.write("textarea.defaultValue is " +
document.surfCity.textareaObj.defaultValue + "<BR>")
msgWindow.document.close()
}

参看

Text.value

form

An object reference specifying the form containing this object.

属性源 | Text
只读 |
实现版本 | Navigator 2.0

描述

每个表单元素都有一个 form 属性用于指向元素的父表单。该属性在事件控制句柄中特别有用，你可能想要由其获得当前表单中其它元素。

示例

示例 1. In the following example, the form myForm contains a Text object and a button. When the user clicks the button, the value of the Text object is set to the form's name. The button's onClick event handler uses this.form to refer to the parent form, myForm.

<FORM NAME="myForm">
Form name:<INPUT TYPE="text" NAME="text1" VALUE="Beluga">
<P>
<INPUT NAME="button1" TYPE="button" VALUE="Show Form Name"
onClick="this.form.text1.value=this.form.name">
</FORM> 示例 2. The following example shows a form with several elements. When the user clicks button2, the function showElements displays an alert dialog box containing the names of each element on the form myForm.

function showElements(theForm) {
str = "Form Elements of form " + theForm.name + ": \n "
for (i = 0; i < theForm.length; i++)
str += theForm.elements[i].name + "\n"
alert(str)
}
</script>
<FORM NAME="myForm">
Form name:<INPUT TYPE="text" NAME="text1" VALUE="Beluga">
<P>
<INPUT NAME="button1" TYPE="button" VALUE="Show Form Name"
onClick="this.form.text1.value=this.form.name">
<INPUT NAME="button2" TYPE="button" VALUE="Show Form Elements"
onClick="showElements(this.form)">
</FORM>
The alert dialog box displays the following text:

JavaScript Alert:
Form Elements of form myForm:
text1
button1
button2 示例 3. The following example uses an object reference, rather than the this keyword, to refer to a form. The code returns a reference to myForm, which is a form containing myTextObject.

document.myForm.myTextObject.form

参看

Form

name

A string specifying the name of this object.

属性源 | Text
实现版本 | Navigator 2.0

安全性

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

描述

The name property initially reflects the value of the NAME attribute. Changing the name property overrides this setting. The name property is not displayed on-screen; it is used to refer to the objects programmatically.

If multiple objects on the same form have the same NAME attribute, an array of the given name is created automatically. Each element in the array represents an individual Form object. Elements are indexed in source order starting at 0. For example, if two Text elements and a Textarea element on the same form have their NAME attribute set to "myField", an array with the elements myField[0], myField[1], and myField[2] is created. You need to be aware of this situation in your code and know whether myField refers to a single element or to an array of elements.

示例

In the following example, the valueGetter function uses a for loop to iterate over the array of elements on the valueTest form. The msgWindow window displays the names of all the elements on the form:

newWindow=window.open("http://home.netscape.com")
function valueGetter() {
var msgWindow=window.open("")
for (var i = 0; i < newWindow.document.valueTest.elements.length; i++) {
msgWindow.document.write(newWindow.document.valueTest.elements[i].name + "<BR>")
}
}

type

For all Text objects, the value of the type property is "text". This property specifies the form element's type.

属性源 | Text
只读 |
实现版本 | Navigator 3.0

示例

The following example writes the value of the type property for every element on a form.

for (var i = 0; i < document.form1.elements.length; i++) {
document.writeln("<BR>type is " + document.form1.elements[i].type)
}

value

A string that reflects the VALUE attribute of the object.

属性源 | Text
实现版本 | Navigator 2.0

安全性

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

描述

The value property is a string that initially reflects the VALUE attribute. This string is displayed in the text field. The value of this property changes when a user or a program modifies the field.

You can set the value property at any time. The display of the Text object updates immediately when you set the value property.

示例

The following function evaluates the value property of a group of buttons and displays it in the msgWindow window:

function valueGetter() {
var msgWindow=window.open("")
msgWindow.document.write("submitButton.value is " +
document.valueTest.submitButton.value + "<BR>")
msgWindow.document.write("resetButton.value is " +
document.valueTest.resetButton.value + "<BR>")
msgWindow.document.write("myText.value is " +
document.valueTest.myText.value + "<BR>")
msgWindow.document.close()
} This example displays the following:

submitButton.value is Query Submit
resetButton.value is Reset
myText.value is Stonefish are dangerous. The previous example assumes the buttons have been defined as follows:

<INPUT TYPE="submit" NAME="submitButton">
<INPUT TYPE="reset" NAME="resetButton">
<INPUT TYPE="text" NAME="myText" VALUE="Stonefish are dangerous.">

参看

Text.defaultValue

方法

blur

 Removes focus from the text field.

方法源 | Text
实现版本 | Navigator 2.0

语法

blur()

参数

 无

示例

The following example removes focus from the text element userText:

userText.blur() This example assumes that the text element is defined as

<INPUT TYPE="text" NAME="userText">

参看

Text.focus, Text.select

focus

Navigates to the text field and gives it focus.

方法源 | Text
实现版本 | Navigator 2.0

语法

focus()

参数

 无

描述

Use the focus method to navigate to a text field and give it focus. You can then either programmatically enter a value in the field or let the user enter a value. If you use this method without the select method, the cursor is positioned at the beginning of the field.

示例

See example for select.

参看

Text.blur, Text.select

handleEvent

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

方法源 | Text
实现版本 | Navigator 4.0

语法

handleEvent(event)

参数

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

select

Selects the input area of the text field.

方法源 | Text
实现版本 | Navigator 2.0

语法

select()

参数

 无

描述

Use the select method to highlight the input area of a text field. You can use the select method with the focus method to highlight a field and position the cursor for a user response. This makes it easy for the user to replace all the text in the field.

示例

The following example uses an onClick event handler to move the focus to a text field and select that field for changing:

<FORM NAME="myForm">
<B>Last name: </B><INPUT TYPE="text" NAME="lastName" SIZE=20 VALUE="Pigman">
<BR><B>First name: </B><INPUT TYPE="text" NAME="firstName" SIZE=20 VALUE="Victoria">
<BR><BR>
<INPUT TYPE="button" VALUE="Change last name"
onClick="this.form.lastName.select();this.form.lastName.focus();">
</FORM>

参看

Text.blur, Text.focus


JavaScript语言参考手册_表单

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

Textarea

 A multiline input field on an HTML form. The user can use a textarea field to enter words, phrases, or numbers.

客户端对象 |
实现版本 | Navigator 2.0 Navigator 3.0: 添加了 type 属性. Navigator 4.0: 添加了 handleEvent 方法。

创建源

The HTML TEXTAREA tag. For a given form, the JavaScript runtime engine creates appropriate Textarea objects and puts these objects in the elements array of the corresponding Form object. You access a Textarea object by indexing this array. You can index the array either by number or, if supplied, by using the value of the NAME attribute.

To define a text area, use standard HTML语法 with the addition of JavaScript event handlers.

事件句柄

  • onBlur
  • onChange
  • onFocus
  • onKeyDown
  • onKeyPress
  • onKeyUp
  • onSelect

描述

 A Textarea object on a form looks as follows:

A Textarea object is a form element and must be defined within a FORM tag.

Textarea objects can be updated (redrawn) dynamically by setting the value property (this.value).

To begin a new line in a Textarea object, you can use a newline character. Although this character varies from platform to platform (Unix is \n, Windows is \r, and Macintosh is \n), JavaScript checks for all newline characters before setting a string-valued property and translates them as needed for the user's platform. You could also enter a newline character programmatically--one way is to test the navigator.appVersion property to determine the current platform, then set the newline character accordingly. See navigator.appVersion for an example.

属性概览

defaultValue | Reflects the VALUE attribute.
form | Specifies the form containing the Textarea object.
name | Reflects the NAME attribute.
type | Specifies that the object is a Textarea object.
value | Reflects the current value of the Textarea object.

方法概览

blur | Removes focus from the object.
focus | Gives focus to the object.
handleEvent | 调用指定事件的控制句柄。
select | Selects the input area of the object.

示例

示例 1. The following example creates a Textarea object that is six rows long and 55 columns wide. The textarea field appears immediately below the word "Description:". When the form loads, the Textarea object contains several lines of data, including one blank line.

<B>Description:</B>
<BR><TEXTAREA NAME="item_description" ROWS=6 COLS=55>
Our storage ottoman provides an attractive way to
store lots of CDs and videos--and it's versatile
enough to store other things as well. It can hold up to 72 CDs under the lid and 20 videos
in the drawer below.
</TEXTAREA> 示例 2. The following example creates a string variable containing newline characters for different platforms. When the user clicks the button, the Textarea object is populated with the value from the string variable. The result is three lines of text in the Textarea object.

<SCRIPT>
myString="This is line one.\nThis is line two.\rThis is line three."
</SCRIPT>
<FORM NAME="form1">
<INPUT TYPE="button" Value="Populate the textarea"
onClick="document.form1.textarea1.value=myString">
<P>
<TEXTAREA NAME="textarea1" ROWS=6 COLS=55></TEXTAREA>

参看

Form, Password, String, Text

属性

defaultValue

 A string indicating the default value of a Textarea object.

属性源 | Textarea
实现版本 | Navigator 2.0

安全性

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

描述

The initial value of defaultValue reflects the value specified between the TEXTAREA start and end tags. Setting defaultValue programmatically overrides the initial setting.

You can set the defaultValue property at any time. The display of the related object does not update when you set the defaultValue property, only when you set the value property.

示例

The following function evaluates the defaultValue property of objects on the surfCity form and displays the values in the msgWindow window:

function defaultGetter() {
msgWindow=window.open("")
msgWindow.document.write("hidden.defaultValue is " +
document.surfCity.hiddenObj.defaultValue + "<BR>")
msgWindow.document.write("password.defaultValue is " +
document.surfCity.passwordObj.defaultValue + "<BR>")
msgWindow.document.write("text.defaultValue is " +
document.surfCity.textObj.defaultValue + "<BR>")
msgWindow.document.write("textarea.defaultValue is " +
document.surfCity.textareaObj.defaultValue + "<BR>")
msgWindow.document.close()
}

参看

Textarea.value

form

An object reference specifying the form containing this object.

属性源 | Textarea
只读 |
实现版本 | Navigator 2.0

描述

每个表单元素都有一个 form 属性用于指向元素的父表单。该属性在事件控制句柄中特别有用，你可能想要由其获得当前表单中其它元素。

示例

示例 1. The following example shows a form with several elements. When the user clicks button2, the function showElements displays an alert dialog box containing the names of each element on the form myForm.

function showElements(theForm) {
str = "Form Elements of form " + theForm.name + ": \n "
for (i = 0; i < theForm.length; i++)
str += theForm.elements[i].name + "\n"
alert(str)
}
</script>
<FORM NAME="myForm">
Form name:<INPUT TYPE="textarea" NAME="text1" VALUE="Beluga">
<P>
<INPUT NAME="button1" TYPE="button" VALUE="Show Form Name"
onClick="this.form.text1.value=this.form.name">
<INPUT NAME="button2" TYPE="button" VALUE="Show Form Elements"
onClick="showElements(this.form)">
</FORM>
The alert dialog box displays the following text:

JavaScript Alert:
Form Elements of form myForm:
text1
button1
button2 示例 2. The following example uses an object reference, rather than the this keyword, to refer to a form. The code returns a reference to myForm, which is a form containing myTextareaObject.

document.myForm.myTextareaObject.form

参看

Form

name

A string specifying the name of this object.

属性源 | Textarea
实现版本 | Navigator 2.0

安全性

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

描述

The name property initially reflects the value of the NAME attribute. Changing the name property overrides this setting. The name property is not displayed on-screen; it is used to refer to the objects programmatically.

If multiple objects on the same form have the same NAME attribute, an array of the given name is created automatically. Each element in the array represents an individual Form object. Elements are indexed in source order starting at 0. For example, if two Text elements and a Textarea element on the same form have their NAME attribute set to "myField", an array with the elements myField[0], myField[1], and myField[2] is created. You need to be aware of this situation in your code and know whether myField refers to a single element or to an array of elements.

示例

In the following example, the valueGetter function uses a for loop to iterate over the array of elements on the valueTest form. The msgWindow window displays the names of all the elements on the form:

newWindow=window.open("http://home.netscape.com")
function valueGetter() {
var msgWindow=window.open("")
for (var i = 0; i < newWindow.document.valueTest.elements.length; i++) {
msgWindow.document.write(newWindow.document.valueTest.elements[i].name + "<BR>")
}
}

type

For all Textarea objects, the value of the type property is "textarea". This property specifies the form element's type.

属性源 | Textarea
只读 |
实现版本 | Navigator 3.0

示例

The following example writes the value of the type property for every element on a form.

for (var i = 0; i < document.form1.elements.length; i++) {
document.writeln("<BR>type is " + document.form1.elements[i].type)
}

value

A string that initially reflects the VALUE attribute.

属性源 | Textarea
实现版本 | Navigator 2.0

安全性

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

描述

This string is displayed in the textarea field. The value of this property changes when a user or a program modifies the field.

You can set the value property at any time. The display of the Textarea object updates immediately when you set the value property.

示例

The following function evaluates the value property of a group of buttons and displays it in the msgWindow window:

function valueGetter() {
var msgWindow=window.open("")
msgWindow.document.write("submitButton.value is " +
document.valueTest.submitButton.value + "<BR>")
msgWindow.document.write("resetButton.value is " +
document.valueTest.resetButton.value + "<BR>")
msgWindow.document.write("blurb.value is " +
document.valueTest.blurb.value + "<BR>")
msgWindow.document.close()
} This example displays the following:

submitButton.value is Query Submit
resetButton.value is Reset
blurb.value is Tropical waters contain all sorts of cool fish,
such as the harlequin ghost pipefish, dragonet, and cuttlefish.
A cuttlefish looks much like a football wearing a tutu and a mop. The previous example assumes the buttons have been defined as follows:

<INPUT TYPE="submit" NAME="submitButton">
<INPUT TYPE="reset" NAME="resetButton">
<TEXTAREA NAME="blurb" rows=3 cols=60>
Tropical waters contain all sorts of cool fish,
such as the harlequin ghost pipefish, dragonet, and cuttlefish.
A cuttlefish looks much like a football wearing a tutu and a mop.
</TEXTAREA>

参看

Textarea.defaultValue

方法

blur

 Removes focus from the object.

方法源 | Textarea
实现版本 | Navigator 2.0

语法

blur()

参数

 无

示例

The following example removes focus from the textarea element userText:

userText.blur() This example assumes that the textarea is defined as

<TEXTAREA NAME="userText">
Initial text for the text area.
</TEXTAREA>

参看

Textarea.focus, Textarea.select

focus

Navigates to the textarea field and gives it focus.

方法源 | Textarea
实现版本 | Navigator 2.0

语法

focus()

参数

 无

描述

Use the focus method to navigate to the textarea field and give it focus. You can then either programmatically enter a value in the field or let the user enter a value. If you use this method without the select method, the cursor is positioned at the beginning of the field.

参看

Textarea.blur, Textarea.select

示例

See example for Textarea.select.

handleEvent

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

方法源 | Textarea
实现版本 | Navigator 4.0

语法

handleEvent(event)

参数

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

描述

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

select

Selects the input area of the object.

方法源 | Textarea
实现版本 | Navigator 2.0

语法

select()

参数

 无

描述

Use the select method to highlight the input area of a textarea field. You can use the select method with the focus method to highlight the field and position the cursor for a user response. This makes it easy for the user to replace all the text in the field.

示例

The following example uses an onClick event handler to move the focus to a textarea field and select that field for changing:

<FORM NAME="myForm">
<B>Last name: </B><INPUT TYPE="text" NAME="lastName" SIZE=20 VALUE="Pigman">
<BR><B>First name: </B><INPUT TYPE="text" NAME="firstName" SIZE=20 VALUE="Victoria">
<BR><B>Description:</B>
<BR><TEXTAREA NAME="desc" ROWS=3 COLS=40>An avid scuba diver.</TEXTAREA>
<BR><BR>
<INPUT TYPE="button" VALUE="Change描述"
onClick="this.form.desc.select();this.form.desc.focus();">
</FORM>

参看

Textarea.blur, Textarea.focus


JavaScript语言参考手册_表单

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

Password

 A text field on an HTML form that conceals its value by displaying asterisks (*). When the user enters text into the field, asterisks (*) hide entries from view.

客户端对象 |
实现版本 | Navigator 2.0 Navigator 3.0: 添加了 type 属性; 添加了 onBlur and onFocus event handlers Navigator 4.0: 添加了 handleEvent 方法。

创建源

The HTML INPUT tag, with "password" as the value of the TYPE attribute. For a given form, the JavaScript runtime engine creates appropriate Password objects and puts these objects in the elements array of the corresponding Form object. You access a Password object by indexing this array. You can index the array either by number or, if supplied, by using the value of the NAME attribute.

事件句柄

  • onBlur
  • onFocus

描述

 A Password object on a form looks as follows:

A Password object is a form element and must be defined within a FORM tag.

安全性

Navigator 3.0: If a user interactively modifies the value in a password field, you cannot evaluate it accurately unless data tainting is enabled. See the JavaScript Guide.

属性概览

defaultValue | Reflects the VALUE attribute.
form | Specifies the form containing the Password object.
name | Reflects the NAME attribute.
type | Reflects the TYPE attribute.
value | Reflects the current value of the Password object's field.

方法概览

blur | Removes focus from the object.
focus | Gives focus to the object.
handleEvent | 调用指定事件的控制句柄。
select | Selects the input area of the object.

示例

The following example creates a Password object with no default value:

<B>Password:</B>
<INPUT TYPE="password" NAME="password" VALUE="" SIZE=25>

参看

Form, Text

属性

defaultValue

 A string indicating the default value of a Password object.

属性源 | Password
实现版本 | Navigator 2.0

安全性

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

描述

The initial value of defaultValue is null (for security reasons), regardless of the value of the VALUE attribute.

Setting defaultValue programmatically overrides the initial setting. If you programmatically set defaultValue for the Password object and then evaluate it, JavaScript returns the current value.

You can set the defaultValue property at any time. The display of the related object does not update when you set the defaultValue property, only when you set the value property.

参看

Password.value

form

An object reference specifying the form containing this object.

属性源 | Password
只读 |
实现版本 | Navigator 2.0

描述

每个表单元素都有一个 form 属性用于指向元素的父表单。该属性在事件控制句柄中特别有用，你可能想要由其获得当前表单中其它元素。

name

A string specifying the name of this object.

属性源 | Password
实现版本 | Navigator 2.0

安全性

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

描述

The name property initially reflects the value of the NAME attribute. Changing the name property overrides this setting. The name property is not displayed on-screen; it is used to refer to the objects programmatically.

If multiple objects on the same form have the same NAME attribute, an array of the given name is created automatically. Each element in the array represents an individual Form object. Elements are indexed in source order starting at 0. For example, if two Text elements and a Password element on the same form have their NAME attribute set to "myField", an array with the elements myField[0], myField[1], and myField[2] is created. You need to be aware of this situation in your code and know whether myField refers to a single element or to an array of elements.

示例

In the following example, the valueGetter function uses a for loop to iterate over the array of elements on the valueTest form. The msgWindow window displays the names of all the elements on the form:

newWindow=window.open("http://home.netscape.com")
function valueGetter() {
var msgWindow=window.open("")
for (var i = 0; i < newWindow.document.valueTest.elements.length; i++) {
msgWindow.document.write(newWindow.document.valueTest.elements[i].name + "<BR>")
}
}

type

For all Password objects, the value of the type property is "password". This property specifies the form element's type.

属性源 | Password
只读 |
实现版本 | Navigator 3.0

示例

The following example writes the value of the type property for every element on a form.

for (var i = 0; i < document.form1.elements.length; i++) {
document.writeln("<BR>type is " + document.form1.elements[i].type)
}

value

A string that initially reflects the VALUE attribute.

属性源 | Password
实现版本 | Navigator 2.0

安全性

Navigator 3.0：该属性默认是带有污点的。有关数据污点的更多信息，请看“JavaScript 的安全性”。 If you programmatically set the value property and then evaluate it, JavaScript returns the current value. If a user interactively modifies the value in the password field, you cannot evaluate it accurately unless data tainting is enabled. See the JavaScript Guide.

描述

This string is represented by asterisks in the Password object field. The value of this property changes when a user or a program modifies the field, but the value is always displayed as asterisks.

参看

Password.defaultValue

方法

blur

 Removes focus from the object.

方法源 | Password
实现版本 | Navigator 2.0

语法

blur()

参数

 无

示例

The following example removes focus from the password element userPass:

userPass.blur() This example assumes that the password is defined as

<INPUT TYPE="password" NAME="userPass">

参看

Password.focus, Password.select

focus

Gives focus to the password object.

方法源 | Password
实现版本 | Navigator 2.0

语法

focus()

参数

 无

描述

Use the focus method to navigate to the password field and give it focus. You can then either programmatically enter a value in the field or let the user enter a value.

示例

In the following example, the checkPassword function confirms that a user has entered a valid password. If the password is not valid, the focus method returns focus to the Password object and the select method highlights it so the user can reenter the password.

function checkPassword(userPass) {
if (badPassword) {
alert("Please enter your password again.")
userPass.focus()
userPass.select()
}
}
This example assumes that the Password object is defined as

<INPUT TYPE="password" NAME="userPass">

参看

Password.blur, Password.select

handleEvent

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

方法源 | Password
实现版本 | Navigator 4.0

语法

handleEvent(event)

参数

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

描述

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

select

Selects the input area of the password field.

方法源 | Password
实现版本 | Navigator 2.0

语法

select()

参数

 无

描述

Use the select method to highlight the input area of the password field. You can use the select method with the focus method to highlight a field and position the cursor for a user response.

示例

In the following example, the checkPassword function confirms that a user has entered a valid password. If the password is not valid, the select method highlights the password field and the focus method returns focus to it so the user can reenter the password.

function checkPassword(userPass) {
if (badPassword) {
alert("Please enter your password again.")
userPass.focus()
userPass.select()
}
}
This example assumes that the password is defined as

<INPUT TYPE="password" NAME="userPass">

参看

Password.blur, Password.focus


JavaScript语言参考手册_表单

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

FileUpload

 A file upload element on an HTML form. A file upload element lets the user supply a file as input.

客户端对象 |
实现版本 | Navigator 2.0 Navigator 3.0: 添加了 type 属性 Navigator 4.0: 添加了 handleEvent 方法。

创建源

The HTML INPUT tag, with "file" as the value of the TYPE attribute. For a given form, the JavaScript runtime engine creates appropriate FileUpload objects and puts these objects in the elements array of the corresponding Form object. You access a FileUpload object by indexing this array. You can index the array either by number or, if supplied, by using the value of the NAME attribute.

事件句柄

  • onBlur
  • onChange
  • onFocus

描述

 A FileUpload object on a form looks as follows:

A FileUpload object is a form element and must be defined within a FORM tag.

属性概览

form | Specifies the form containing the FileUpload object.
name | Reflects the NAME attribute.
type | Reflects the TYPE attribute.
value | Reflects the current value of the file upload element's field; this corresponds to the name of the file to upload.

方法概览

blur | Removes focus from the object.
focus | Gives focus to the object.
handleEvent | 调用指定事件的控制句柄。
select | Selects the input area of the file upload field.

示例

The following example places a FileUpload object on a form and provides two buttons that let the user display current values of the name and value properties.

<FORM NAME="form1">
File to send: <INPUT TYPE="file" NAME="myUploadObject">
<P>Get properties<BR>
<INPUT TYPE="button" VALUE="name"
onClick="alert('name: ' + document.form1.myUploadObject.name)">
<INPUT TYPE="button" VALUE="value"
onClick="alert('value: ' + document.form1.myUploadObject.value)"><BR>
</FORM>

参看

Text

属性

form

 An object reference specifying the form containing the object.

属性源 | FileUpload
只读 |
实现版本 | Navigator 2.0

描述

每个表单元素都有一个 form 属性用于指向元素的父表单。该属性在事件控制句柄中特别有用，你可能想要由其获得当前表单中其它元素。

name

A string specifying the name of this object.

属性源 | FileUpload
只读 |
实现版本 | Navigator 2.0

安全性

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

描述

The name property initially reflects the value of the NAME attribute. The name property is not displayed on-screen; it is used to refer to the objects programmatically.

If multiple objects on the same form have the same NAME attribute, an array of the given name is created automatically. Each element in the array represents an individual Form object. Elements are indexed in source order starting at 0. For example, if two Text elements and a FileUpload element on the same form have their NAME attribute set to "myField", an array with the elements myField[0], myField[1], and myField[2] is created. You need to be aware of this situation in your code and know whether myField refers to a single element or to an array of elements.

示例

In the following example, the valueGetter function uses a for loop to iterate over the array of elements on the valueTest form. The msgWindow window displays the names of all the elements on the form:

newWindow=window.open("http://home.netscape.com")
function valueGetter() {
var msgWindow=window.open("")
for (var i = 0; i < newWindow.document.valueTest.elements.length; i++) {
msgWindow.document.write(newWindow.document.valueTest.elements[i].name + "<BR>")
}
}

type

For all FileUpload objects, the value of the type property is "file". This property specifies the form element's type.

属性源 | FileUpload
只读 |
实现版本 | Navigator 3.0

示例

The following example writes the value of the type property for every element on a form.

for (var i = 0; i < document.form1.elements.length; i++) {
document.writeln("<BR>type is " + document.form1.elements[i].type)
}

value

A string that reflects the VALUE attribute of the object.

属性源 | FileUpload
只读 |
实现版本 | Navigator 2.0

安全性

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

Navigator 4.0: Setting a file upload widget requires the UniversalFileRead privilege. 要获取 Navigator 4.0 中关于安全性更多的信息，请看“JavaScript 指南”中的第七章“JavaScript 安全性”。

描述

Use the value property to obtain the file name that the user typed into a FileUpload object.

方法

blur

 Removes focus from the object.

方法源 | FileUpload
实现版本 | Navigator 2.0

语法

blur()

参数

 无

参看

FileUpload.focus, FileUpload.select

focus

Navigates to the FileUpload field and give it focus.

方法源 | FileUpload
实现版本 | Navigator 2.0

语法

focus()

参数

 无

参看

FileUpload.blur, FileUpload.select

handleEvent

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

语法

handleEvent(event)

方法源 | FileUpload
实现版本 | Navigator 4.0

参数

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

描述

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

select

Selects the input area of the file upload field.

方法源 | FileUpload
实现版本 | Navigator 2.0

语法

select()

参数

 无

描述

Use the select method to highlight the input area of a file upload field. You can use the select method with the focus method to highlight a field and position the cursor for a user response. This makes it easy for the user to replace all the text in the field.

参看

FileUpload.blur, FileUpload.focus


JavaScript语言参考手册_窗口

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

第六章
窗口

这一章讲解了 Window 对象及其在客户端关联的对象：Frame、Location 和 History 。

表 6.1 本章用到的对象总览。

表 6.1 Window 对象
对象 | 描述
Frame | 可以在同一屏幕上显示多个互不干涉的可滚动框架的窗口，每个框架有其自己的 URL 。
History | 包含了一组客户已经在窗口中浏览过的 URL 的信息。
Location | 包含了当前 URL 的信息。
screen | 包含了描述显示屏幕和颜色的属性。
Window | 描述了一个浏览器窗口或框架。这是每个 document、Location 和 History 对象组的顶级对象。

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


JavaScript语言参考手册_窗口

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

Window

 Represents a browser window or frame. This is the top-level object for each document, Location, and History object group.

客户端对象
实现版本 Navigator 2.0
Navigator 3.0: 添加了 closed, history, and opener properties; 添加了 blur, focus, and scroll 方法; 添加了 onBlur, onError, and onFocus event handlers
Navigator 4.0: 添加了 innerHeight, innerWidth, locationbar, menubar, outerHeight, outerWidth, pageXOffset, pageYOffset, personalbar, scrollbars, statusbar, and toolbar properties; 添加了 back, captureEvents, clearInterval, disableExternalCapture, enableExternalCapture, find, forward, handleEvent, home, moveBy, moveTo, releaseEvents, resizeBy, resizeTo, routeEvent, scrollBy, scrollTo, setInterval, and stop 方法s; deprecated scroll 方法。

创建源

The JavaScript runtime engine creates a Window object for each BODY or FRAMESET tag. It also creates a Window object to represent each frame defined in a FRAME tag. In addition, you can create other windows by calling the Window.open method. For details on defining a window, see open.

事件句柄

  • onBlur
  • onDragDrop
  • onError
  • onFocus
  • onLoad
  • onMove
  • onResize
  • onUnload
In Navigator 3.0, on some platforms, placing an onBlur or onFocus event handler in a FRAMESET tag has no effect.

描述

The Window object is the top-level object in the JavaScript client hierarchy. A Window object can represent either a top-level window or a frame inside a frameset. As a matter of convenience, you can think about a Frame object as a Window object that isn't a top-level window. However, there is not really a separate Frame class; these objects really are Window objects, with a very few minor differences:

  • For a top-level window, the parent and top properties are references to the window itself. For a frame, the top refers to the topmost browser window, and parent refers to the parent window of the current window.

  • For a top-level window, setting the defaultStatus or status property sets the text appearing in the browser status line. For a frame, setting these properties only sets the status line text when the cursor is over the frame.

  • The close method is not useful for windows that are frames.

  • To create an onBlur or onFocus event handler for a frame, you must set the onblur or onfocus property and specify it in all lowercase (you cannot specify it in HTML).

  • If a FRAME tag contains SRC and NAME attributes, you can refer to that frame from a sibling frame by using parent.frameName or parent.frames【索引】. For example, if the fourth frame in a set has NAME="homeFrame", sibling frames can refer to that frame using parent.homeFrame or parent.frames[3].
For all windows, the self and window properties of a Window object are synonyms for the current window, and you can optionally use them to refer to the current window. For example, you can close the current window by calling the close method of either window or self. You can use these properties to make your code more readable or to disambiguate the property reference self.status from a form called status. See the properties and methods listed below for more示例.

Because the existence of the current window is assumed, you do not have to refer to the name of the window when you call its methods and assign its properties. For example, status="Jump to a new location" is a valid property assignment, and close() is a valid method call.

However, when you open or close a window within an event handler, you must specify window.open() or window.close() instead of simply using open() or close(). Due to the scoping of static objects in JavaScript, a call to close() without specifying an object name is equivalent to document.close().

For the same reason, when you refer to the location object within an event handler, you must specify window.location instead of simply using location. A call to location without specifying an object name is equivalent to document.location, which is a synonym for document.URL.

You can refer to a window's Frame objects in your code by using the frames array. In a window with a FRAMESET tag, the frames array contains an entry for each frame.

A windows lacks event handlers until HTML that contains a BODY or FRAMESET tag is loaded into it.

属性概览

closed | Specifies whether a window has been closed.
defaultStatus | Reflects the default message displayed in the window's status bar.
document | Contains information on the current document, and provides 方法s for displaying HTML output to the user.
frames | An array reflecting all the frames in a window.
history | Contains information on the URLs that the client has visited within a window.
innerHeight | Specifies the vertical dimension, in pixels, of the window's content area.
innerWidth | Specifies the horizontal dimension, in pixels, of the window's content area.
length | The number of frames in the window.
location | Contains information on the current URL.
locationbar | Represents the browser window's location bar.
menubar | Represents the browser window's menu bar.
name | A unique name used to refer to this window.
opener | Specifies the window name of the calling document when a window is opened using the open 方法
outerHeight | Specifies the vertical dimension, in pixels, of the window's outside boundary.
outerWidth | Specifies the horizontal dimension, in pixels, of the window's outside boundary.
pageXOffset | Provides the current x-position, in pixels, of a window's viewed page.
pageYOffset | Provides the current y-position, in pixels, of a window's viewed page.
parent | A synonym for a window or frame whose frameset contains the current frame.
personalbar | Represents the browser window's personal bar (also called the directories bar).
scrollbars | Represents the browser window's scroll bars.
self | A synonym for the current window.
status | Specifies a priority or transient message in the window's status bar.
statusbar | Represents the browser window's status bar.
toolbar | Represents the browser window's tool bar.
top | A synonym for the topmost browser window.
window | A synonym for the current window.

方法概览

alert | Displays an Alert dialog box with a message and an OK button.
back | Undoes the last history step in any frame within the top-level window.
blur | Removes focus from the specified object.
captureEvents | Sets the window or document to capture all events of the specified type.
clearInterval | Cancels a timeout that was set with the setInterval 方法。
clearTimeout | Cancels a timeout that was set with the setTimeout 方法。
close | Closes the specified window.
confirm | Displays a Confirm dialog box with the specified message and OK and Cancel buttons.
disableExternalCapture | Disables external event capturing set by the enableExternalCapture 方法。
enableExternalCapture | Allows a window with frames to capture events in pages loaded from different locations (servers).
find | Finds the specified text string in the contents of the specified window.
focus | Gives focus to the specified object.
forward | Loads the next URL in the history list.
handleEvent | 调用指定事件的控制句柄。
home | Points the browser to the URL specified in preferences as the user's home page.
moveBy | Moves the window by the specified amounts.
moveTo | Moves the top-left corner of the window to the specified screen coordinates.
open | Opens a new web browser window.
print | Prints the contents of the window or frame.
prompt | Displays a Prompt dialog box with a message and an input field.
releaseEvents | Sets the window to release captured events of the specified type, sending the event to objects further along the event hierarchy.
resizeBy | Resizes an entire window by moving the window's bottom-right corner by the specified amount.
resizeTo | Resizes an entire window to the specified outer height and width.
routeEvent | Passes a captured event along the normal event hierarchy.
scroll | Scrolls a window to a specified coordinate.
scrollBy | Scrolls the viewing area of a window by the specified amount.
scrollTo | Scrolls the viewing area of the window to the specified coordinates, such that the specified point becomes the top-left corner.
setInterval | Evaluates an expression or calls a function every time a specified number of milliseconds elapses.
setTimeout | Evaluates an expression or calls a function once after a specified number of milliseconds has elapsed.
stop | Stops the current download.

示例

示例 1. Windows opening other windows. In the following example, the document in the top window opens a second window, window2, and defines push buttons that open a message window, write to the message window, close the message window, and close window2. The onLoad and onUnload event handlers of the document loaded into window2 display alerts when the window opens and closes.

win1.html, which defines the frames for the first window, contains the following code:

<HTML>
<HEAD>
<TITLE>Window object example: Window 1</TITLE>
</HEAD>
<BODY BGCOLOR="antiquewhite">
<SCRIPT>
window2=open("win2.html","secondWindow",
"scrollbars=yes,width=250, height=400")
document.writeln("<B>The first window has no name: "
+ window.name + "</B>")
document.writeln("<BR><B>The second window is named: "
+ window2.name + "</B>")
</SCRIPT>
<FORM NAME="form1">
<P><INPUT TYPE="button" VALUE="Open a message window"
onClick = "window3=window.open('','messageWindow',
'scrollbars=yes,width=175, height=300')">
<P><INPUT TYPE="button" VALUE="Write to the message window"
onClick="window3.document.writeln('Hey there');
window3.document.close()">
<P><INPUT TYPE="button" VALUE="Close the message window"
onClick="window3.close()">
<P><INPUT TYPE="button" VALUE="Close window2"
onClick="window2.close()">
</FORM>
</BODY>
</HTML> win2.html, which defines the content for window2, contains the following code:

<HTML>
<HEAD>
<TITLE>Window object example: Window 2</TITLE>
</HEAD>
<BODY BGCOLOR="oldlace"
onLoad="alert('Message from ' + window.name + ': Hello, World.')"
onUnload="alert('Message from ' + window.name + ': I\'m closing')">
<B>Some numbers</B>
<UL><LI>one
<LI>two
<LI>three
<LI>four</UL>
</BODY>
</HTML> 示例 2. Creating frames. The following example creates two windows, each with four frames. In the first window, the first frame contains push buttons that change the background colors of the frames in both windows. framset1.html, which defines the frames for the first window, contains the following code:

<HTML>
<HEAD>
<TITLE>Frames and Framesets: Window 1</TITLE>
</HEAD>
<FRAMESET ROWS="50%,50%" COLS="40%,60%"
onLoad="alert('Hello, World.')">
<FRAME SRC=framcon1.html NAME="frame1">
<FRAME SRC=framcon2.html NAME="frame2">
<FRAME SRC=framcon2.html NAME="frame3">
<FRAME SRC=framcon2.html NAME="frame4">
</FRAMESET>
</HTML> framset2.html, which defines the frames for the second window, contains the following code:

<HTML>
<HEAD>
<TITLE>Frames and Framesets: Window 2</TITLE>
</HEAD>
<FRAMESET ROWS="50%,50%" COLS="40%,60%">
<FRAME SRC=framcon2.html NAME="frame1">
<FRAME SRC=framcon2.html NAME="frame2">
<FRAME SRC=framcon2.html NAME="frame3">
<FRAME SRC=framcon2.html NAME="frame4">
</FRAMESET>
</HTML> framcon1.html, which defines the content for the first frame in the first window, contains the following code:

<HTML>
<BODY>
<A NAME="frame1"><H1>Frame1</H1></A>
<P><A HREF="framcon3.htm" target=frame2>Click here</A>
to load a different file into frame 2.
<SCRIPT>
window2=open("framset2.htm","secondFrameset")
</SCRIPT>
<FORM>
<P><INPUT TYPE="button" VALUE="Change frame2 to teal"
onClick="parent.frame2.document.bgColor='teal'">
<P><INPUT TYPE="button" VALUE="Change frame3 to slateblue"
onClick="parent.frames[2].document.bgColor='slateblue'">
<P><INPUT TYPE="button" VALUE="Change frame4 to darkturquoise"
onClick="top.frames[3].document.bgColor='darkturquoise'">
<P><INPUT TYPE="button" VALUE="window2.frame2 to violet"
onClick="window2.frame2.document.bgColor='violet'">
<P><INPUT TYPE="button" VALUE="window2.frame3 to fuchsia"
onClick="window2.frames[2].document.bgColor='fuchsia'">
<P><INPUT TYPE="button" VALUE="window2.frame4 to deeppink"
onClick="window2.frames[3].document.bgColor='deeppink'">
</FORM>
</BODY>
</HTML>
framcon2.html, which defines the content for the remaining frames, contains the following code:

<HTML>
<BODY>
<P>This is a frame.
</BODY>
</HTML> framcon3.html, which is referenced in a Link object in framcon1.html, contains the following code:

<HTML>
<BODY>
<P>This is a frame. What do you think?
</BODY>
</HTML>

参看

document, Frame

属性

closed

 Specifies whether a window is closed.

属性源 | Window
只读 |
实现版本 | Navigator 3.0

描述

The closed property is a boolean value that specifies whether a window has been closed. When a window closes, the window object that represents it continues to exist, and its closed property is set to true.

Use closed to determine whether a window that you opened, and to which you still hold a reference (from the return value of window.open), is still open. Once a window is closed, you should not attempt to manipulate it.

示例

示例 1. The following code opens a window, win1, then later checks to see if that window has been closed. A function is called depending on whether win1 is closed.

win1=window.open('opener1.html','window1','width=300,height=300')
...
if (win1.closed)
function1()
else
function2() 示例 2. The following code determines if the current window's opener window is still closed, and calls the appropriate function.

if (window.opener.closed)
function1()
else
function2()

参看

Window.close, Window.open

defaultStatus

The default message displayed in the status bar at the bottom of the window.

属性源 | Window
实现版本 | Navigator 2.0

安全性

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

描述

The defaultStatus message appears when nothing else is in the status bar. Do not confuse the defaultStatus property with the status property. The status property reflects a priority or transient message in the status bar, such as the message that appears when a mouseOver event occurs over an anchor.

You can set the defaultStatus property at any time. You must return true if you want to set the defaultStatus property in the onMouseOut or onMouseOver event handlers.

示例

In the following example, the statusSetter function sets both the status and defaultStatus properties in an onMouseOver event handler:

function statusSetter() {
window.defaultStatus = "Click the link for the Netscape home page"
window.status = "Netscape home page"
}
<A HREF="http://home.netscape.com"
onMouseOver = "statusSetter(); return true">Netscape</A>
In the previous example, notice that the onMouseOver event handler returns a value of true. You must return true to set status or defaultStatus in an event handler.

参看

Window.status

document

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

属性源 | Window
实现版本 | Navigator 2.0

描述

The value of this property is the window's associated document object.

frames

An array of objects corresponding to child frames (created with the FRAME tag) in source order.

属性源 | Window
只读 |
实现版本 | Navigator 2.0

You can refer to the child frames of a window by using the frames array. This array contains an entry for each child frame (created with the FRAME tag) in a window containing a FRAMESET tag; the entries are in source order. For example, if a window contains three child frames whose NAME attributes are fr1, fr2, and fr3, you can refer to the objects in the images array either as:

parent.frames["fr1"]
parent.frames["fr2"]
parent.frames["fr3"] or as:

parent.frames[0]
parent.frames[1]
parent.frames[2] You can find out how many child frames the window has by using the length property of the Window itself or of the frames array.

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

history

Contains information on the URLs that the client has visited within a window.

属性源 | Window
实现版本 | Navigator 3.0

描述

The value of this property is the window's associated History object.

innerHeight

Specifies the vertical dimension, in pixels, of the window's content area.

属性源 | Window
实现版本 | Navigator 4.0

描述

To create a window smaller than 100 x 100 pixels, set this property in a signed script.

安全性

To set the inner height of a window to a size smaller than 100 x 100 or larger than the screen can accommodate, you need the UniversalBrowserWrite privilege. 要获取 Navigator 4.0 中关于安全性更多的信息，请看“JavaScript 指南”中的第七章“JavaScript 安全性”。

参看

Window.innerWidth, Window.outerHeight, Window.outerWidth

innerWidth

Specifies the horizontal dimension, in pixels, of the window's content area.

属性源 | Window
实现版本 | Navigator 4.0

描述

To create a window smaller than 100 x 100 pixels, set this property in a signed script.

安全性

To set the inner width of a window to a size smaller than 100 x 100 or larger than the screen can accommodate, you need the UniversalBrowserWrite privilege. 要获取 Navigator 4.0 中关于安全性更多的信息，请看“JavaScript 指南”中的第七章“JavaScript 安全性”。

参看

Window.innerHeight, Window.outerHeight, Window.outerWidth

length

The number of child frames in the window.

属性源 | Window
只读 |
实现版本 | Navigator 2.0

描述

This property gives you the same result as using the length property of the frames array.

location

Contains information on the current URL.

属性源 | Window
实现版本 | Navigator 2.0

描述

The value of this property is the window's associated Location object.

locationbar

Represents the browser window's location bar (the region containing the bookmark and URL areas).

属性源 | Window
实现版本 | Navigator 4.0

描述

The value of the locationbar property itself has one property, visible. If true, the location bar is visible; if false, it is hidden.

安全性

Setting the value of the location bar's visible property requires the UniversalBrowserWrite privilege. 要获取 Navigator 4.0 中关于安全性更多的信息，请看“JavaScript 指南”中的第七章“JavaScript 安全性”。

示例

The following example would make the referenced window "chromeless" (chromeless windows lack toolbars, scrollbars, status areas, and so on, much like a dialog box) by hiding most of the user interface toolbars:

self.menubar.visible=false;
self.toolbar.visible=false;
self.locationbar.visible=false;
self.personalbar.visible=false;
self.scrollbars.visible=false;
self.statusbar.visible=false;

menubar

Represents the browser window's menu bar. This region contains browser's drop-down menus such as File, Edit, View, Go, Communicator, and so on.

属性源 | Window
实现版本 | Navigator 4.0

描述

The value of the menubar property itself one property, visible. If true, the menu bar is visible; if false, it is hidden.

安全性

Setting the value of the menu bar's visible property requires the UniversalBrowserWrite privilege. 要获取 Navigator 4.0 中关于安全性更多的信息，请看“JavaScript 指南”中的第七章“JavaScript 安全性”。

示例

The following example would make the referenced window "chromeless" (chromeless windows lack toolbars, scrollbars, status areas, and so on, much like a dialog box) by hiding most of the user interface toolbars:

self.menubar.visible=false;
self.toolbar.visible=false;
self.locationbar.visible=false;
self.personalbar.visible=false;
self.scrollbars.visible=false;
self.statusbar.visible=false;

name

A string specifying the window's name.

属性源 | Window
只读 (2.0); Modifiable (later versions)
实现版本 | Navigator 2.0

安全性

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

描述

In Navigator 2.0, NAME was a read-only property. In later versions, this property is modifiable by your code. This allows you to assign a name to a top-level window.

示例

In the following example, the first statement creates a window called netscapeWin. The second statement displays the value "netscapeHomePage" in the Alert dialog box, because "netscapeHomePage" is the value of the windowName argument of netscapeWin.

netscapeWin=window.open("http://home.netscape.com","netscapeHomePage")
alert(netscapeWin.name)

opener

Specifies the window of the calling document when a window is opened using the open method.

属性源 | Window
实现版本 | Navigator 3.0

描述

When a source document opens a destination window by calling the open method, the opener property specifies the window of the source document. Evaluate the opener property from the destination window.

This property persists across document unload in the opened window.

You can change the opener property at any time.

You may use Window.open to open a new window and then use Window.open on that window to open another window, and so on. In this way, you can end up with a chain of opened windows, each of which has an opener property pointing to the window that opened it.

Communicator allows a maximum of 100 windows to be around at once. If you open window2 from window1 and then are done with window1, be sure to set the opener property of window2 to null. This allows JavaScript to garbage collect window1. If you do not set the opener property to null, the window1 object remains, even though it's no longer really needed.

示例

示例 1: Close the opener. The following code closes the window that opened the current window. When the opener window closes, opener is unchanged. However, window.opener.name then evaluates to undefined.

window.opener.close() 示例 2: Close the main browser window.

top.opener.close() 示例 3: Evaluate the name of the opener. A window can determine the name of its opener as follows:

document.write("<BR>opener property is " + window.opener.name) 示例 4: Change the value of opener. The following code changes the value of the opener property to null. After this code executes, you cannot close the opener window as shown in Example 1.

window.opener=null 示例 5: Change a property of the opener. The following code changes the background color of the window specified by the opener property.

window.opener.document.bgColor='bisque'

参看

Window.close, Window.open

outerHeight

Specifies the vertical dimension, in pixels, of the window's outside boundary.

属性源 | Window
实现版本 | Navigator 4.0

描述

The outer boundary includes the scroll bars, the status bar, the tool bars, and other "chrome" (window border user interface elements). To create a window smaller than 100 x 100 pixels, set this property in a signed script.

参看

Window.innerWidth, Window.innerHeight, Window.outerWidth

outerWidth

Specifies the horizontal dimension, in pixels, of the window's outside boundary.

属性源 | Window
实现版本 | Navigator 4.0

描述

The outer boundary includes the scroll bars, the status bar, the tool bars, and other "chrome" (window border user interface elements). To create a window smaller than 100 x 100 pixels, set this property in a signed script.

参看

Window.innerWidth, Window.innerHeight, Window.outerHeight

pageXOffset

Provides the current x-position, in pixels, of a window's viewed page.

属性源 | Window
只读 |
实现版本 | Navigator 4.0

描述

The pageXOffset property provides the current x-position of a page as it relates to the upper-left corner of the window's content area. This property is useful when you need to find the current location of the scrolled page before using scrollTo or scrollBy.

示例

The following example returns the x-position of the viewed page.

x = myWindow.pageXOffset

参看

Window.pageYOffset

pageYOffset

Provides the current y-position, in pixels, of a window's viewed page.

属性源 | Window
只读 |
实现版本 | Navigator 4.0

描述

The pageYOffset property provides the current y-position of a page as it relates to the upper-left corner of the window's content area. This property is useful when you need to find the current location of the scrolled page before using scrollTo or scrollBy.

示例

The following example returns the y-position of the viewed page.

x = myWindow.pageYOffset

参看

Window.pageXOffset

parent

The parent property is the window or frame whose frameset contains the current frame.

属性源 | Window
只读 |
实现版本 | Navigator 2.0

描述

This property is only meaningful for frames; that is, windows that are not top-level windows.

The parent property refers to the FRAMESET window of a frame. Child frames within a frameset refer to sibling frames by using parent in place of the window name in one of the following ways:

parent.frameName
parent.frames【索引】 For example, if the fourth frame in a set has NAME="homeFrame", sibling frames can refer to that frame using parent.homeFrame or parent.frames[3].

You can use parent.parent to refer to the "grandparent" frame or window when a FRAMESET tag is nested within a child frame.

The value of the parent property is

<object nameAttribute> where nameAttribute is the NAME attribute if the parent is a frame, or an internal reference if the parent is a window.

示例

See示例 for Frame.

personalbar

Represents the browser window's personal bar (also called the directories bar). This is the region the user can use for easy access to certain bookmarks.

属性源 | Window
实现版本 | Navigator 4.0

描述

The value of the personalbar property itself one property, visible. If true, the personal bar is visible; if false, it is hidden.

安全性

Setting the value of the personal bar's visible property requires the UniversalBrowserWrite privilege. 要获取 Navigator 4.0 中关于安全性更多的信息，请看“JavaScript 指南”中的第七章“JavaScript 安全性”。

示例

The following example would make the referenced window "chromeless" (chromeless windows lack toolbars, scrollbars, status areas, and so on, much like a dialog box) by hiding most of the user interface toolbars:

self.menubar.visible=false;
self.toolbar.visible=false;
self.locationbar.visible=false;
self.personalbar.visible=false;
self.scrollbars.visible=false;
self.statusbar.visible=false;

scrollbars

Represents the browser window's vertical and horizontal scroll bars for the document area.

属性源 | Window
实现版本 | Navigator 4.0

描述

The value of the scrollbars property itself has one property, visible. If true, both scrollbars are visible; if false, they are hidden.

安全性

Setting the value of the scrollbars' visible property requires the UniversalBrowserWrite privilege. 要获取 Navigator 4.0 中关于安全性更多的信息，请看“JavaScript 指南”中的第七章“JavaScript 安全性”。

示例

The following example would make the referenced window "chromeless" (chromeless windows lack toolbars, scrollbars, status areas, and so on, much like a dialog box) by hiding most of the user interface toolbars:

self.menubar.visible=false;
self.toolbar.visible=false;
self.locationbar.visible=false;
self.personalbar.visible=false;
self.scrollbars.visible=false;
self.statusbar.visible=false;

self

The self property is a synonym for the current window.

属性源 | Window
只读 |
实现版本 | Navigator 2.0

描述

The self property refers to the current window. That is, the value of this property is a synonym for the object itself.

Use the self property to disambiguate a window property from a form or form element of the same name. You can also use the self property to make your code more readable.

The value of the self property is

<object nameAttribute> where nameAttribute is the NAME attribute if self refers to a frame, or an internal reference if self refers to a window.

示例

In the following example, self.status is used to set the status property of the current window. This usage disambiguates the status property of the current window from a form or form element called status within the current window.

<A HREF=""
onClick="this.href=pickRandomURL()"
onMouseOver="self.status='Pick a random URL' ; return true">
Go!</A>

status

Specifies a priority or transient message in the status bar at the bottom of the window, such as the message that appears when a mouseOver event occurs over an anchor.

属性源 | Window
实现版本 | Navigator 2.0

安全性

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

描述

Do not confuse the status property with the defaultStatus property. The defaultStatus property reflects the default message displayed in the status bar.

You can set the status property at any time. You must return true if you want to set the status property in the onMouseOver event handler.

示例

Suppose you have created a JavaScript function called pickRandomURL that lets you select a URL at random. You can use the onClick event handler of an anchor to specify a value for the HREF attribute of the anchor dynamically, and the onMouseOver event handler to specify a custom message for the window in the status property:

<A HREF=""
onClick="this.href=pickRandomURL()"
onMouseOver="self.status='Pick a random URL'; return true">
Go!</A>
In the preceding example, the status property of the window is assigned to the window's self property, as self.status.

参看

Window.defaultStatus

statusbar

Represents the browser window's status bar. This is the region containing the security indicator, browser status, and so on.

属性源 | Window
实现版本 | Navigator 4.0

描述

The value of the statusbar property itself one property, visible. If true, the status bar is visible; if false, it is hidden.

安全性

Setting the value of the status bar's visible property requires the UniversalBrowserWrite privilege. 要获取 Navigator 4.0 中关于安全性更多的信息，请看“JavaScript 指南”中的第七章“JavaScript 安全性”。

示例

The following example would make the referenced window "chromeless" (chromeless windows lack toolbars, scrollbars, status areas, and so on, much like a dialog box) by hiding most of the user interface toolbars:

self.menubar.visible=false;
self.toolbar.visible=false;
self.locationbar.visible=false;
self.personalbar.visible=false;
self.scrollbars.visible=false;
self.statusbar.visible=false;

toolbar

Represents the browser window's tool bar, containing the navigation buttons, such as Back, Forward, Reload, Home, and so on.

属性源 | Window
实现版本 | Navigator 4.0

描述

The value of the toolbar property itself one property, visible. If true, the tool bar is visible; if false, it is hidden.

安全性

Setting the value of the tool bar's visible property requires the UniversalBrowserWrite privilege. 要获取 Navigator 4.0 中关于安全性更多的信息，请看“JavaScript 指南”中的第七章“JavaScript 安全性”。

示例

The following example would make the referenced window "chromeless" (chromeless windows lack toolbars, scrollbars, status areas, and so on, much like a dialog box) by hiding most of the user interface toolbars:

self.menubar.visible=false;
self.toolbar.visible=false;
self.locationbar.visible=false;
self.personalbar.visible=false;
self.scrollbars.visible=false;
self.statusbar.visible=false;

top

The top property is a synonym for the topmost browser window, which is a document window or web browser window.

属性源 | Window
只读 |
实现版本 | Navigator 2.0

描述

The top property refers to the topmost window that contains frames or nested framesets. Use the top property to refer to this ancestor window.

The value of the top property is

<object objectReference> where objectReference is an internal reference.

示例

The statement top.close() closes the topmost ancestor window.

The statement top.length specifies the number of frames contained within the topmost ancestor window. When the topmost ancestor is defined as follows, top.length returns three:

<FRAMESET COLS="30%,40%,30%">
<FRAME SRC=child1.htm NAME="childFrame1">
<FRAME SRC=child2.htm NAME="childFrame2">
<FRAME SRC=child3.htm NAME="childFrame3">
</FRAMESET>
The following example sets the background color of a frame called myFrame to red. myFrame is a child of the topmost ancestor window.

top.myFrame.document.bgColor="red"

window

The window property is a synonym for the current window or frame.

属性源 | Window
只读 |
实现版本 | Navigator 2.0

描述

The window property refers to the current window or frame. That is, the value of this property is a synonym for the object itself.

Although you can use the window property as a synonym for the current frame, your code may be more readable if you use the self property. For example, window.name and self.name both specify the name of the current frame, but self.name may be easier to understand (because a frame is not displayed as a separate window).

Use the window property to disambiguate a property of the window object from a form or form element of the same name. You can also use the window property to make your code more readable.

The value of the window property is

<object nameAttribute> where nameAttribute is the NAME attribute if window refers to a frame, or an internal reference if window refers to a window.

示例

In the following example, window.status is used to set the status property of the current window. This usage disambiguates the status property of the current window from a form called "status" within the current window.

<A HREF=""
onClick="this.href=pickRandomURL()"
onMouseOver="window.status='Pick a random URL' ; return true">
Go!</A>

参看

Window.self

方法

alert

 Displays an Alert dialog box with a message and an OK button.

方法源 | Window
实现版本 | Navigator 2.0

语法

alert("message")

参数

message A string.

描述

An alert dialog box looks as follows:

Use the alert method to display a message that does not require a user decision. The message argument specifies a message that the dialog box contains.

You cannot specify a title for an alert dialog box, but you can use the open method to create your own alert dialog box. See open.

示例

In the following example, the testValue function checks the name entered by a user in the Text object of a form to make sure that it is no more than eight characters in length. This example uses the alert method to prompt the user to enter a valid value.

function testValue(textElement) {
if (textElement.length > 8) {
alert("Please enter a name that is 8 characters or less")
}
} You can call the testValue function in the onBlur event handler of a form's Text object, as shown in the following example:

Name: <INPUT TYPE="text" NAME="userName"
onBlur="testValue(userName.value)">

参看

Window.confirm, Window.prompt

back

Undoes the last history step in any frame within the top-level window; equivalent to the user pressing the browser's Back button.

方法源 | Window
实现版本 | Navigator 4.0

语法

back()

参数

 无

描述

Calling the back method is equivalent to the user pressing the browser's Back button. That is, back undoes the last step anywhere within the top-level window, whether it occurred in the same frame or in another frame in the tree of frames loaded from the top-level window. In contrast, the history object's back method backs up the current window or frame history one step.

For example, consider the following scenario. While in Frame A, you click the Forward button to change Frame A's content. You then move to Frame B and click the Forward button to change Frame B's content. If you move back to Frame A and call FrameA.back(), the content of Frame B changes (clicking the Back button behaves the same).

If you want to navigate Frame A separately, use FrameA.history.back().

示例

The following custom buttons perform the same operation as the browser's Back button:

<P><INPUT TYPE="button" VALUE="< Go Back"
onClick="history.back()">
<P><INPUT TYPE="button" VALUE="> Go Back"
onClick="myWindow.back()">

参看

Window.forward, History.back

blur

Removes focus from the specified object.

方法源 | Window
实现版本 | Navigator 2.0

语法

blur()

参数

 无

描述

Use the blur method to remove focus from a specific window or frame. Removing focus from a window sends the window to the background in most windowing systems.

参看

Window.focus

captureEvents

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

方法源 | Window
实现版本 | Navigator 4.0

语法

captureEvents(eventType)

参数

eventType The 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 captureEvents in a signed script and precede it with enableExternalCapture. You must have the UniversalBrowserWrite privilege. For more information and an example, see enableExternalCapture. 要获取 Navigator 4.0 中关于安全性更多的信息，请看“JavaScript 指南”中的第七章“JavaScript 安全性”。

参看

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

clearInterval

 Cancels a timeout that was set with the setInterval method.

方法源 | Window
实现版本 | Navigator 4.0

语法

clearInterval(intervalID)

参数

intervalID Timeout setting that was returned by a previous call to the setInterval 方法。

描述

See setInterval.

示例

See setInterval.

参看

Window.setInterval

clearTimeout

Cancels a timeout that was set with the setTimeout method.

方法源 | Window
实现版本 | Navigator 2.0

语法

clearTimeout(timeoutID)

参数

timeoutID A timeout setting that was returned by a previous call to the setTimeout 方法。

描述

See setTimeout.

示例

See setTimeout.

参看

Window.clearInterval, Window.setTimeout

close

Closes the specified window.

方法源 | Window
实现版本 | Navigator 2.0: closes any window. Navigator 3.0: closes only windows opened by JavaScript. Navigator 4.0: must use signed scripts to unconditionally close a window.

语法

close()

参数

 无

安全性

Navigator 4.0: To unconditionally close a window, you need the UniversalBrowserWrite privilege. 要获取 Navigator 4.0 中关于安全性更多的信息，请看“JavaScript 指南”中的第七章“JavaScript 安全性”。

描述

The close method closes the specified window. If you call close without specifying a windowReference, JavaScript closes the current window.

The close method closes only windows opened by JavaScript using the open method. If you attempt to close any other window, a confirm is generated, which lets the user choose whether the window closes. This is a security feature to prevent "mail bombs" containing self.close(). However, if the window has only one document (the current one) in its session history, the close is allowed without any confirm. This is a special case for one-off windows that need to open other windows and then dispose of themselves.

In event handlers, you must specify window.close() instead of simply using close(). Due to the scoping of static objects in JavaScript, a call to close() without specifying an object name is equivalent to document.close().

示例

示例 1. Any of the following示例 closes the current window:

window.close()
self.close()
close()
示例 2: Close the main browser window. The following code closes the main browser window.

top.opener.close() 示例 3. The following example closes the messageWin window:

messageWin.close() This example assumes that the window was opened in a manner similar to the following:

messageWin=window.open("")

参看

Window.closed, Window.open

confirm

Displays a Confirm dialog box with the specified message and OK and Cancel buttons.

方法源 | Window
实现版本 | Navigator 2.0

语法

confirm("message")

参数

message A string.

描述

A confirm dialog box looks as follows:

Use the confirm method to ask the user to make a decision that requires either an OK or a Cancel. The message argument specifies a message that prompts the user for the decision. The confirm method returns true if the user chooses OK and false if the user chooses Cancel.

You cannot specify a title for a confirm dialog box, but you can use the open method to create your own confirm dialog. See open.

示例

This example uses the confirm method in the confirmCleanUp function to confirm that the user of an application really wants to quit. If the user chooses OK, the custom cleanUp function closes the application.

function confirmCleanUp() {
if (confirm("Are you sure you want to quit this application?")) {
cleanUp()
}
}
You can call the confirmCleanUp function in the onClick event handler of a form's push button, as shown in the following example:

<INPUT TYPE="button" VALUE="Quit" onClick="confirmCleanUp()">

参看

Window.alert, Window.prompt

disableExternalCapture

Disables external event capturing set by the enableExternalCapture method.

方法源 | Window
实现版本 | Navigator 4.0

语法

disableExternalCapture()

参数

 无

描述

See enableExternalCapture.

enableExternalCapture

Allows a window with frames to capture events in pages loaded from different locations (servers).

方法源 | Window
实现版本 | Navigator 4.0

语法

enableExternalCapture()

参数

 无

描述

Use this method in a signed script requesting UniversalBrowserWrite privileges, and use it before calling the captureEvents method.

If Communicator sees additional scripts that cause the set of principals in effect for the container to be downgraded, it disables external capture of events. Additional calls to enableExternalCapture (after acquiring the UniversalBrowserWrite privilege under the reduced set of principals) can be made to enable external capture again.

示例

In the following example, the window is able to capture all Click events that occur across its frames.

<SCRIPT ARCHIVE="myArchive.jar" ID="2">
function captureClicks() {
netscape.security.PrivilegeManager.enablePrivilege(
"UniversalBrowserWrite");
enableExternalCapture();
captureEvents(Event.CLICK);
...
}
</SCRIPT>

参看

Window.disableExternalCapture, Window.captureEvents

find

Finds the specified text string in the contents of the specified window.

方法源 | Window
实现版本 | Navigator 4.0

语法

find(string, casesensitive, backward)

参数

string | (Optional) The text string for which to search.
casesensitive | (Optional) Boolean value. If true, specifies a case-sensitive search. If you supply this parameter, you must also supply backward.
backward | (Optional) Boolean. If true, specifies a backward search. If you supply this parameter, you must also supply casesensitive.

返回

true if the string is found; otherwise, false.

描述

When a string is specified, the browser performs a case-insensitive, forward search. If a string is not specified, the method displays the Find dialog box, allowing the user to enter a search string.

focus

Gives focus to the specified object.

方法源 | Window
实现版本 | Navigator 3.0

语法

focus()

参数

 无

描述

Use the focus method to navigate to a specific window or frame, and give it focus. Giving focus to a window brings the window forward in most windowing systems.

In Navigator 3.0, on some platforms, the focus method gives focus to a frame but the focus is not visually apparent (for example, the frame's border is not darkened).

示例

In the following example, the checkPassword function confirms that a user has entered a valid password. If the password is not valid, the focus method returns focus to the Password object and the select method highlights it so the user can reenter the password.

function checkPassword(userPass) {
if (badPassword) {
alert("Please enter your password again.")
userPass.focus()
userPass.select()
}
}
This example assumes that the Password object is defined as

<INPUT TYPE="password" NAME="userPass">

参看

Window.blur

forward

Points the browser to the next URL in the current history list; equivalent to the user pressing the browser's Forward button

方法源 | Window
实现版本 | Navigator 4.0

语法

history.forward() forward()

参数

 无

描述

This method performs the same action as a user choosing the Forward button in the browser. The forward method is the same as history.go(1).

When used with the Frame object, forward behaves as follows: While in Frame A, you click the Back button to change Frame A's content. You then move to Frame B and click the Back button to change Frame B's content. If you move back to Frame A and call FrameA.forward(), the content of Frame B changes (clicking the Forward button behaves the same). If you want to navigate Frame A separately, use FrameA.history.forward().

示例

The following custom buttons perform the same operation as the browser's Forward button:

<P><INPUT TYPE="button" VALUE="< Go Forth"
onClick="history.forward()">
<P><INPUT TYPE="button" VALUE="> Go Forth"
onClick="myWindow.forward()">

参看

Window.back

handleEvent

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

方法源 | Window
实现版本 | Navigator 4.0

语法

handleEvent(event)

参数

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

描述

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

home

 Points the browser to the URL specified in preferences as the user's home page; equivalent to the user pressing the browser's Home button.

方法源 | Window
实现版本 | Navigator 4.0

语法

home()

参数

 无

描述

This method performs the same action as a user choosing the Home button in the browser.

moveBy

Moves the window relative to its current position, moving the specified number of pixels.

方法源 | Window
实现版本 | Navigator 4.0

语法

moveBy(horizontal, vertical)

参数

horizontal | The number of pixels by which to move the window horizontally.
vertical | The number of pixels by which to move the window vertically.

描述

This method moves the window by adding or subtracting the specified number of pixels to the current location.

安全性

Exceeding any of the boundaries of the screen (to hide some or all of a window) requires signed JavaScript, so a window won't move past the screen boundaries. You need the UniversalBrowserWrite privilege for this. 要获取 Navigator 4.0 中关于安全性更多的信息，请看“JavaScript 指南”中的第七章“JavaScript 安全性”。

示例:

To move the current window 5 pixels up towards the top of the screen (x-axis), and 10 pixels towards the right (y-axis) of the current window position, use this statement:

self.moveBy(-5,10); // relative positioning

参看

Window.moveTo

moveTo

Moves the top-left corner of the window to the specified screen coordinates.

方法源 | Window
实现版本 | Navigator 4.0

语法

moveTo(x-coordinate, y-coordinate)

参数

x-coordinate | The left edge of the window in screen coordinates.
y-coordinate | The top edge of the window in screen coordinates.

描述

This method moves the window to the absolute pixel location indicated by its parameters. The origin of the axes is at absolute position (0,0); this is the upper left-hand corner of the display.

安全性

Exceeding any of the boundaries of the screen (to hide some or all of a window) requires signed JavaScript, so a window won't move past the screen boundaries. You need the UniversalBrowserWrite privilege for this. 要获取 Navigator 4.0 中关于安全性更多的信息，请看“JavaScript 指南”中的第七章“JavaScript 安全性”。

示例:

To move the current window to 25 pixels from the top boundary of the screen (x-axis), and 10 pixels from the left boundary of the screen (y-axis), use this statement:

self.moveTo(25,10); // absolute positioning

参看

Window.moveBy

open

Opens a new web browser window.

方法源 | Window
实现版本 | Navigator 2.0 Navigator 4.0: 添加了 several new windowFeatures

语法

open(URL, windowName, windowFeatures)

参数

URL | A string specifying the URL to open in the new window. See the Location object for a描述 of the URL components.
windowName | A string specifying the window name to use in the TARGET attribute of a FORM or A tag. windowName can contain only alphanumeric or underscore (_) characters.
windowFeatures | (Optional) A string containing a comma-separated list determining whether or not to create various standard window features. These options are described below.

描述

In event handlers, you must specify window.open() instead of simply using open(). Due to the scoping of static objects in JavaScript, a call to open() without specifying an object name is equivalent to document.open().

The open method opens a new Web browser window on the client, similar to choosing New Navigator Window from the File menu of the browser. The URL argument specifies the URL contained by the new window. If URL is an empty string, a new, empty window is created.

You can use open on an existing window, and if you pass the empty string for the URL, you will get a reference to the existing window, but not load anything into it. You can, for example, then look for properties in the window.

windowFeatures is an optional string containing a comma-separated list of options for the new window (do not include any spaces in this list). After a window is open, you cannot use JavaScript to change the windowFeatures. The features you can specify are:

alwaysLowered | (Navigator 4.0) If yes, creates a new window that floats below other windows, whether it is active or not. This is a secure feature and must be set in signed scripts.
alwaysRaised | (Navigator 4.0) If yes, creates a new window that floats on top of other windows, whether it is active or not. This is a secure feature and must be set in signed scripts.
dependent | (Navigator 4.0) If yes, creates a new window as a child of the current window. A dependent window closes when its parent window closes. On Windows platforms, a dependent window does not show on the task bar.
directories | If yes, creates the standard browser directory buttons, such as What's New and What's Cool.
height | (Navigator 2.0 and 3.0) Specifies the height of the window in pixels.
hotkeys | (Navigator 4.0) If no (or 0), disables most hotkeys in a new window that has no menu bar. The security and quit hotkeys remain enabled.
innerHeight | (Navigator 4.0) Specifies the height, in pixels, of the window's content area. To create a window smaller than 100 x 100 pixels, set this feature in a signed script. This feature replaces height, which remains for backwards compatibility.
innerWidth | (Navigator 4.0) Specifies the width, in pixels, of the window's content area. To create a window smaller than 100 x 100 pixels, set this feature in a signed script. This feature replaces width, which remains for backwards compatibility.
location | If yes, creates a Location entry field.
menubar | If yes, creates the menu at the top of the window.
outerHeight | (Navigator 4.0) Specifies the vertical dimension, in pixels, of the outside boundary of the window. To create a window smaller than 100 x 100 pixels, set this feature in a signed script.
resizable | If yes, allows a user to resize the window.
screenX | (Navigator 4.0) Specifies the distance the new window is placed from the left side of the screen. To place a window offscreen, set this feature in a signed scripts.
screenY | (Navigator 4.0) Specifies the distance the new window is placed from the top of the screen. To place a window offscreen, set this feature in a signed scripts.
scrollbars | If yes, creates horizontal and vertical scrollbars when the Document grows larger than the window dimensions.
status | If yes, creates the status bar at the bottom of the window.
titlebar | (Navigator 4.0) If yes, creates a window with a title bar. To set the titlebar to no, set this feature in a signed script.
toolbar | If yes, creates the standard browser toolbar, with buttons such as Back and Forward.
width | (Navigator 2.0 and 3.0) Specifies the width of the window in pixels.
z-lock | (Navigator 4.0) If yes, creates a new window that does not rise above other windows when activated. This is a secure feature and must be set in signed scripts.

Many of these features (as noted above) can either be yes or no. For these features, you can use 1 instead of yes and 0 instead of no. If you want to turn a feature on, you can also simply list the feature name in the windowFeatures string.

If windowName does not specify an existing window and you do not supply the windowFeatures parameter, all of the features which have a yes/no choice are yes by default. However, if you do supply the windowFeatures parameter, then the titlebar and hotkeys are still yes by default, but the other features which have a yes/no choice are no by default.

For example, all of the following statements turn on the toolbar option and turn off all other Boolean options:

open("", "messageWindow", "toolbar")
open("", "messageWindow", "toolbar=yes")
open("", "messageWindow", "toolbar=1")
The following statement turn on the location and directories options and turns off all other Boolean options:

open("", "messageWindow", "toolbar,directories=yes") How the alwaysLowered, alwaysRaised, and z-lock features behave depends on the windowing hierarchy of the platform. For example, on Windows, an alwaysLowered or z-locked browser window is below all windows in all open applications. On Macintosh, an alwaysLowered browser window is below all browser windows, but not necessarily below windows in other open applications. Similarly for an alwaysRaised window.

You may use open to open a new window and then use open on that window to open another window, and so on. In this way, you can end up with a chain of opened windows, each of which has an opener property pointing to the window that opened it.

Communicator allows a maximum of 100 windows to be around at once. If you open window2 from window1 and then are done with window1, be sure to set the opener property of window2 to null. This allows JavaScript to garbage collect window1. If you do not set the opener property to null, the window1 object remains, even though it's no longer really needed.

安全性

To perform the following operations using the specified screen features, you need the UniversalBrowserWrite privilege:

  • To create a window smaller than 100 x 100 pixels or larger than the screen can accommodate by using innerWidth, innerHeight, outerWidth, and outerHeight.

  • To place a window off screen by using screenX and screenY.

  • To create a window without a titlebar by using titlebar.

  • To use alwaysRaised, alwaysLowered, or z-lock for any setting.
要获取 Navigator 4.0 中关于安全性更多的信息，请看“JavaScript 指南”中的第七章“JavaScript 安全性”。

示例

示例 1. In the following example, the windowOpener function opens a window and uses write methods to display a message:

function windowOpener() {
msgWindow=window.open("","displayWindow","menubar=yes")
msgWindow.document.write
("<HEAD><TITLE>Message window</TITLE></HEAD>")
msgWindow.document.write
("<CENTER><BIG><B>Hello, world!</B></BIG></CENTER>")
} 示例 2. The following is an onClick event handler that opens a new client window displaying the content specified in the file sesame.html. The window opens with the specified option settings; all other options are false because they are not specified.

<FORM NAME="myform">
<INPUT TYPE="button" NAME="Button1" VALUE="Open Sesame!"
onClick="window.open ('sesame.html', 'newWin',
'scrollbars=yes,status=yes,width=300,height=300')">
</FORM>

参看

Window.close

print

Prints the contents of the window.

方法源 | Window
实现版本 | Navigator 4.0

语法

print()

参数

 无

prompt

Displays a Prompt dialog box with a message and an input field.

方法源 | Window
实现版本 | Navigator 2.0

语法

prompt(message, inputDefault)

参数

message | A string to be displayed as the message.
inputDefault | (Optional) A string or integer representing the default value of the input field.

描述

A prompt dialog box looks as follows:

Use the prompt method to display a dialog box that receives user input. If you do not specify an initial value for inputDefault, the dialog box displays <undefined>.

You cannot specify a title for a prompt dialog box, but you can use the open method to create your own prompt dialog. See open.

示例

prompt("Enter the number of cookies you want to order:", 12)

参看

 Window.alert, Window.confirm

releaseEvents

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

方法源 | Window
实现版本 | 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)

参数

eventType Type of event to be captured.

描述

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

resizeBy

Resizes an entire window by moving the window's bottom-right corner by the specified amount.

方法源 | Window
实现版本 | Navigator 4.0

语法

resizeBy(horizontal, vertical)

参数

horizontal | The number of pixels by which to resize the window horizontally.
vertical | The number of pixels by which to resize the window vertically.

描述

This method changes the window's dimensions by setting its outerWidth and outerHeight properties. The upper left-hand corner remains anchored and the lower right-hand corner moves. resizeBy moves the window by adding or subtracting the specified number of pixels to that corner's current location.

安全性

Exceeding any of the boundaries of the screen (to hide some or all of a window) requires signed JavaScript, so a window won't move past the screen boundaries. In addition, windows have an enforced minimum size of 100 x 100 pixels; resizing a window to be smaller than this minimum requires signed JavaScript. You need the UniversalBrowserWrite privilege for this. 要获取 Navigator 4.0 中关于安全性更多的信息，请看“JavaScript 指南”中的第七章“JavaScript 安全性”。

示例

To make the current window 5 pixels narrower and 10 pixels taller than its current dimensions, use this statement:

self.resizeBy(-5,10); // relative positioning

参看

Window.resizeTo

resizeTo

Resizes an entire window to the specified pixel dimensions.

方法源 | Window
实现版本 | Navigator 4.0

语法

resizeTo(outerWidth, outerHeight)

参数

outerWidth | An integer representing the window's width in pixels.
outerHeight | An integer representing the window's height in pixels.

描述

This method changes the window's dimensions by setting its outerWidth and outerHeight properties. The upper left-hand corner remains anchored and the lower right-hand corner moves. resizeBy moves to the specified position. The origin of the axes is at absolute position (0,0); this is the upper left-hand corner of the display.

安全性

Exceeding any of the boundaries of the screen (to hide some or all of a window) requires signed JavaScript, so a window won't move past the screen boundaries. In addition, windows have an enforced minimum size of 100 x 100 pixels; resizing a window to be smaller than this minimum requires signed JavaScript. You need the UniversalBrowserWrite privilege for this. 要获取 Navigator 4.0 中关于安全性更多的信息，请看“JavaScript 指南”中的第七章“JavaScript 安全性”。

示例

To make the window 225 pixels wide and 200 pixels tall, use this statement:

self.resizeTo(225,200); // absolute positioning

参看

Window.resizeBy

routeEvent

Passes a captured event along the normal event hierarchy.

方法源 | Window
实现版本 | Navigator 4.0

语法

routeEvent(event)

参数

event Name 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".

scroll

Scrolls a window to a specified coordinate.

方法源 | Window
实现版本 | Navigator 3.0; deprecated in 4.0

描述

In Navigator 4.0, scroll is no longer used and has been replaced by scrollTo. scrollTo extends the capabilities of scroll. scroll remains for backward compatibility.

scrollBy

 Scrolls the viewing area of a window by the specified amount.

方法源 | Window
实现版本 | Navigator 4.0

语法

scrollBy(horizontal, vertical)

参数

horizontal | The number of pixels by which to scroll the viewing area horizontally.
vertical | The number of pixels by which to scroll the viewing area vertically.

描述

This method scrolls the content in the window if portions that can't be seen exist outside of the window. scrollBy scrolls the window by adding or subtracting the specified number of pixels to the current scrolled location.

For this method to have an effect the visible property of Window.scrollbars must be true.

示例

To scroll the current window 5 pixels towards the left and 30 pixels down from the current position, use this statement:

self.scrollBy(-5,30); // relative positioning

参看

Window.scrollTo

scrollTo

Scrolls the viewing area of the window so that the specified point becomes the top-left corner.

方法源 | Window
实现版本 | Navigator 4.0

语法

scrollTo(x-coordinate, y-coordinate)

参数

x-coordinate | An integer representing the x-coordinate of the viewing area in pixels.
y-coordinate | An integer representing the y-coordinate of the viewing area in pixels.

描述

scrollTo replaces scroll. scroll remains for backward compatibility.

The scrollTo method scrolls the content in the window if portions that can't be seen exist outside of the window. For this method to have an effect the visible property of Window.scrollbars must be true.

示例

示例 1: Scroll the current viewing area. To scroll the current window to the leftmost boundary and 20 pixels down from the top of the window, use this statement:

self.scrollTo(0,20); // absolute positioning 示例 2: Scroll a different viewing area. The following code, which exists in one frame, scrolls the viewing area of a second frame. Two Text objects let the user specify the x and y coordinates. When the user clicks the Go button, the document in frame2 scrolls to the specified coordinates.

<SCRIPT>
function scrollIt(form) {
var x = parseInt(form.x.value)
var y = parseInt(form.y.value)
parent.frame2.scrollTo(x, y)
}
</SCRIPT>
<BODY> <FORM NAME="myForm">
<P><B>Specify the coordinates to scroll to:</B>
<BR>Horizontal:
<INPUT TYPE="text" NAME=x VALUE="0" SIZE=4>
<BR>Vertical:
<INPUT TYPE="text" NAME=y VALUE="0" SIZE=4>
<BR><INPUT TYPE="button" VALUE="Go"
onClick="scrollIt(document.myForm)">
</FORM>

参看

Window.scrollBy

setInterval

Evaluates an expression or calls a function every time a specified number of milliseconds elapses, until canceled by a call to clearInterval.

方法源 | Window
实现版本 | Navigator 4.0

语法

setInterval(expression, msec)
setInterval(function, msec, arg1, ..., argN)

参数

function | Any function.
expression | A string containing a JavaScript expression. The expression must be quoted; otherwise, setInterval calls it immediately. For example, setInterval("calcnum(3, 2)", 25).
msec | A numeric value or numeric string, in millisecond units.
arg1, ..., argn | (Optional) The arguments, if any, passed to function.

描述

The timeouts continue to fire until the associated window or frame is destroyed or the interval is canceled using the clearInterval method.

参看

Window.clearInterval, Window.setTimeout

setTimeout

Evaluates an expression or calls a function once after a specified number of milliseconds elapses.

方法源 | Window
实现版本 | Navigator 2.0: Evaluating an expression. Navigator 4.0: Calling a function.

语法

setTimeout(expression, msec)
setTimeout(function, msec, arg1, ..., argN)

参数

expression | A string containing a JavaScript expression. The expression must be quoted; otherwise, setTimeout calls it immediately. For example, setTimeout("calcnum(3, 2)", 25).
msec | A numeric value or numeric string, in millisecond units.
function | Any function.
arg1, ..., argN | (Optional) The arguments, if any, passed to function.

描述

The setTimeout method evaluates an expression or calls a function after a specified amount of time. It does not act repeatedly. For example, if a setTimeout method specifies five seconds, the expression is evaluated or the function is called after five seconds, not every five seconds. For repetitive timeouts, use the setInterval method.

setTimeout does not stall the script. The script continues immediately (not waiting for the timeout to expire). The call simply schedules an additional future event.

示例

示例 1. The following example displays an alert message five seconds (5,000 milliseconds) after the user clicks a button. If the user clicks the second button before the alert message is displayed, the timeout is canceled and the alert does not display.

<SCRIPT LANGUAGE="JavaScript">
function displayAlert() {
alert("5 seconds have elapsed since the button was clicked.")
}
</SCRIPT>
<BODY>
<FORM>
Click the button on the left for a reminder in 5 seconds;
click the button on the right to cancel the reminder before
it is displayed.
<P>
<INPUT TYPE="button" VALUE="5-second reminder"
NAME="remind_button"
onClick="timerID=setTimeout('displayAlert()',5000)">
<INPUT TYPE="button" VALUE="Clear the 5-second reminder"
NAME="remind_disable_button"
onClick="clearTimeout(timerID)">
</FORM>
</BODY> 示例 2. The following example displays the current time in a Text object. The showtime function, which is called recursively, uses the setTimeout method to update the time every second.

<HEAD>
<SCRIPT LANGUAGE="JavaScript">
<!--
var timerID = null
var timerRunning = false
function stopclock(){
if(timerRunning)
clearTimeout(timerID)
timerRunning = false
}
function startclock(){
// Make sure the clock is stopped
stopclock()
showtime()
}
function showtime(){
var now = new Date()
var hours = now.getHours()
var minutes = now.getMinutes()
var seconds = now.getSeconds()
var timeValue = "" + ((hours > 12) ? hours - 12 : hours)
timeValue += ((minutes < 10) ? ":0" : ":") + minutes
timeValue += ((seconds < 10) ? ":0" : ":") + seconds
timeValue += (hours >= 12) ? " P.M." : " A.M."
document.clock.face.value = timeValue
timerID = setTimeout("showtime()",1000)
timerRunning = true
}
//-->
</SCRIPT>
</HEAD>
<BODY onLoad="startclock()">
<FORM NAME="clock" onSubmit="0">
<INPUT TYPE="text" NAME="face" SIZE=12 VALUE ="">
</FORM>
</BODY>

参看

Window.clearTimeout, Window.setInterval

stop

Stops the current download.

方法源 | Window
实现版本 | Navigator 4.0

语法

stop()

参数

 无

Definition

This method performs the same action as a user choosing the Stop button in the browser.


JavaScript语言参考手册_窗口

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

Frame

一个窗口可以在一个屏幕上显示多个互不相干的可滚动的框架，每个框架都有其对应的 URL 。这些框架是使用包含在 FRAMESET 标签中的 FRAME 标签创建的。在同一个屏幕中，框架可以指向不同的 URL，并且可以由其它 URL 指向。一系列框架组成一页。Frame 对象提供了一种访问这些框架对应的对象的便捷途径。但是，JavaScript实际上是用 Window 对象描述框架的。每个 Frame 对象都是一个 Window 对象，并且拥有 Window 对象所有的方法和属性。而作为框架的窗口和顶级窗口是有一些不同的。请看 Window 以获得关于框架的完整信息。

客户端对象 |
实现版本 | Navigator 2.0 Navigator 3.0: 添加了 blur 和 focus 方法; 添加了 onBlur 和 onFocus 事件处理控制


JavaScript语言参考手册_窗口

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

Location

 包含了关于当前 URL 的信息。

客户端对象 |
实现版本 | Navigator 2.0 Navigator 3.0: 添加了 reload, replace 方法

创建源

Location 对象是预先定义的 JavaScript 对象，你可以通过一个 Window 对象的 location 属性访问。

描述

location 对象描述了与一个给定的 Window 对象关联的完整 URL。location 对象的每个属性都描述了 URL 的不同特性。

通常情况下，一个 URL 会有下面的格式：

协议//主机:端口/路径名称#哈希标识?搜索条件 例如：

http://home.netscape.com/assist/extensions.html#topic1?x=7&y=2 这些部分是满足下列需求的：

  • “协议”是 URL 的起始部分，直到包含到第一个冒号。

  • “主机”描述了主机和域名，或者一个网络主机的 IP 地址。

  • “端口”描述了服务器用于通讯的通讯端口。

  • 路径名称描述了 URL 的路径方面的信息。

  • “哈希标识”描述了 URL 中的锚名称，包括哈希掩码(#)。此属性只应用于 HTTP 的 URL。

  • “搜索条件”描述了该 URL 中的任何查询信息，包括问号。此属性只应用于 HTTP 的 URL。“搜索条件”字符串包含变量和值的配对；每对之间由一个“&”连接。
A Location object has a property for each of these parts of the URL. See the individual properties for more information. A Location object has two other properties not shown here:

  • href represents a complete URL.

  • hostname represents the concatenation host:port.
If you assign a string to the location property of an object, JavaScript creates a location object and assigns that string to its href property. For example, the following two statements are equivalent and set the URL of the current window to the Netscape home page:

window.location.href="http://home.netscape.com/"
window.location="http://home.netscape.com/" The location object is contained by the window object and is within its scope. If you refer to a location object without specifying a window, the location object represents the current location. If you refer to a location object and specify a window name, as in windowReference.location, the location object represents the location of the specified window.

In event handlers, you must specify window.location instead of simply using location. Due to the scoping of static objects in JavaScript, a call to location without specifying an object name is equivalent to document.location, which is a synonym for document.URL.

Location is not a property of the document object; its equivalent is the document.URL property. The document.location property, which is a synonym for document.URL, will be removed in a future release.

How documents are loaded when location is set

When you set the location object or any of its properties except hash, whether a new document is loaded depends on which version of the browser you are running:

  • In Navigator 2.0, setting location does a conditional ("If-modified-since") HTTP GET operation, which returns no data from the server unless the document has been modified since the last version downloaded.

  • In Navigator 3.0 and later, the effect of setting location depends on the user's setting for comparing a document to the original over the network. The user interface option for setting this preference differs in browser versions. The user decides whether to check a document in cache every time it is accessed, once per session, or never. The document is reloaded from cache if the user sets never or once per session; the document is reloaded from the server only if the user chooses every time.

语法 for common URL types

 When you specify a URL, you can use standard URL formats and JavaScript statements. 表 6.2 shows the语法 for specifying some of the most common types of URLs.

表 6.2 URL语法.
URL type | Protocol | Example
JavaScript code | javascript: | javascript:history.go(-1)
Navigator source viewer | view-source: | view-source:wysiwyg://0/file:/c|/temp/genhtml.html
Navigator info | about: | about:cache
World Wide Web | http: | http://home.netscape.com/
File | file:/ | file:///javascript/方法s.html
FTP | ftp: | ftp://ftp.mine.com/home/mine
MailTo | mailto: | mailto:info@netscape.com
Usenet | news: | news://news.scruznet.com/comp.lang.javascript
Gopher | gopher: | gopher.myhost.com

The javascript: protocol evaluates the expression after the colon (:), if there is one, and loads a page containing the string value of the expression, unless it is undefined. If the expression evaluates to undefined (by calling a void function, for example javascript:void(0)), no new page loads. Note that loading a new page over your script's page clears the page's variables, functions, and so on.

The view-source: protocol displays HTML code that was generated with JavaScript document.write and document.writeln methods. For information on printing and saving generated HTML, see write.

The about: protocol provides information on Navigator and has the following语法:

about:
about:cache
about:plugins

  • about: by itself is the same as choosing About Communicator from the Navigator Help menu.

  • about:cache displays disk-cache statistics.

  • about:plugins displays information about plug-ins you have configured. This is the same as choosing About Plug-ins from the Navigator Help menu.

属性概览

hash | Specifies an anchor name in the URL.
host | Specifies the host and domain name, or IP address, of a network host.
hostname | Specifies the host:port portion of the URL.
href | Specifies the entire URL.
pathname | Specifies the URL-path portion of the URL.
port | Specifies the communications port that the server uses.
protocol | Specifies the beginning of the URL, including the colon.
search | Specifies a query.

方法概览

reload | Forces a reload of the window's current document.
replace | Loads the specified URL over the current history entry.

示例

示例 1. The following two statements are equivalent and set the URL of the current window to the Netscape home page:

window.location.href="http://home.netscape.com/"
window.location="http://home.netscape.com/" 示例 2. The following statement sets the URL of a frame named frame2 to the Sun home page:

parent.frame2.location.href="http://www.sun.com/" See also the示例 for Anchor.

参看

History, document.URL

属性

hash

 A string beginning with a hash mark (#) that specifies an anchor name in the URL.

属性源 | Location
实现版本 | Navigator 2.0

安全性

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

描述

The hash property specifies a portion of the URL. This property applies to HTTP URLs only.

You can set the hash property at any time, although it is safer to set the href property to change a location. If the hash that you specify cannot be found in the current location, you get an error.

Setting the hash property navigates to the named anchor without reloading the document. This differs from the way a document is loaded when other location properties are set (see "How documents are loaded when location is set").

See RFC 1738 (http://www.cis.ohio-state.edu/htbin/rfc/rfc1738.html) for complete information about the hash.

示例

In the following example, the window.open statement creates a window called newWindow and loads the specified URL into it. The document.write statements display properties of newWindow.location in a window called msgWindow.

newWindow=window.open
("http://home.netscape.com/comprod/products/navigator/
version_2.0/script/script_info/objects.html#checkbox_object") msgWindow.document.write("newWindow.location.href = " +
newWindow.location.href + "<P>")
msgWindow.document.write("newWindow.location.hash = " +
newWindow.location.hash + "<P>")
msgWindow.document.close() The previous example displays output such as the following:

newWindow.location.href =
http://home.netscape.com/comprod/products/navigator/
version_2.0/script/script_info/objects.html#checkbox_object
newWindow.location.hash = #checkbox_object

参看

Location.host, Location.hostname, Location.href, Location.pathname, Location.port, Location.protocol, Location.search

host

A string specifying the server name, subdomain, and domain name.

属性源 | Location
实现版本 | Navigator 2.0

安全性

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

描述

The host property specifies a portion of a URL. The host property is a substring of the hostname property. The hostname property is the concatenation of the host and port properties, separated by a colon. When the port property is null, the host property is the same as the hostname property.

You can set the host property at any time, although it is safer to set the href property to change a location. If the host that you specify cannot be found in the current location, you get an error.

See Section 3.1 of RFC 1738 (http://www.cis.ohio-state.edu/htbin/rfc/rfc1738.html) for complete information about the hostname and port.

示例

In the following example, the window.open statement creates a window called newWindow and loads the specified URL into it. The document.write statements display properties of newWindow.location in a window called msgWindow.

newWindow=window.open
("http://home.netscape.com/comprod/products/navigator/
version_2.0/script/script_info/objects.html#checkbox_object") msgWindow.document.write("newWindow.location.href = " +
newWindow.location.href + "<P>")
msgWindow.document.write("newWindow.location.host = " +
newWindow.location.host + "<P>")
msgWindow.document.close() The previous example displays output such as the following:

newWindow.location.href =
http://home.netscape.com/comprod/products/navigator/
version_2.0/script/script_info/objects.html#checkbox_object
newWindow.location.host = home.netscape.com

参看

Location.hash, Location.hostname, Location.href, Location.pathname, Location.port, Location.protocol, Location.search

hostname

A string containing the full hostname of the server, including the server name, subdomain, domain, and port number.

属性源 | Location
实现版本 | Navigator 2.0

安全性

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

描述

The hostname property specifies a portion of a URL. The hostname property is the concatenation of the host and port properties, separated by a colon. When the port property is 80 (the default), the host property is the same as the hostname property.

You can set the hostname property at any time, although it is safer to set the href property to change a location. If the hostname that you specify cannot be found in the current location, you get an error.

See Section 3.1 of RFC 1738 (http://www.cis.ohio-state.edu/htbin/rfc/rfc1738.html) for complete information about the hostname.

示例

In the following example, the window.open statement creates a window called newWindow and loads the specified URL into it. The document.write statements display properties of newWindow.location in a window called msgWindow.

newWindow=window.open
("http://home.netscape.com/comprod/products/navigator/
version_2.0/script/script_info/objects.html#checkbox_object") msgWindow.document.write("newWindow.location.href = " +
newWindow.location.href + "<P>")
msgWindow.document.write("newWindow.location.hostName = " +
newWindow.location.hostName + "<P>")
msgWindow.document.close() The previous example displays output such as the following:

newWindow.location.href =
http://home.netscape.com/comprod/products/navigator/
version_2.0/script/script_info/objects.html#checkbox_object
newWindow.location.hostName = home.netscape.com

参看

Location.hash, Location.host, Location.href, Location.pathname, Location.port, Location.protocol, Location.search

href

A string specifying the entire URL.

属性源 | Location
实现版本 | Navigator 2.0

安全性

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

描述

The href property specifies the entire URL. Other location object properties are substrings of the href property. If you want to change the URL associated with a window, you should do so by changing the href property; this correctly updates all of the other properties.

You can set the href property at any time.

Omitting a property name from the location object is equivalent to specifying location.href. For example, the following two statements are equivalent and set the URL of the current window to the Netscape home page:

window.location.href="http://home.netscape.com/"
window.location="http://home.netscape.com/" See RFC 1738 (http://www.cis.ohio-state.edu/htbin/rfc/rfc1738.html) for complete information about the URL.

示例

In the following example, the window.open statement creates a window called newWindow and loads the specified URL into it. The document.write statements display all the properties of newWindow.location in a window called msgWindow.

newWindow=window.open
("http://home.netscape.com/comprod/products/navigator/
version_2.0/script/script_info/objects.html#checkbox_object") msgWindow.document.write("newWindow.location.href = " +
newWindow.location.href + "<P>")
msgWindow.document.write("newWindow.location.protocol = " +
newWindow.location.protocol + "<P>")
msgWindow.document.write("newWindow.location.host = " +
newWindow.location.host + "<P>")
msgWindow.document.write("newWindow.location.hostName = " +
newWindow.location.hostName + "<P>")
msgWindow.document.write("newWindow.location.port = " +
newWindow.location.port + "<P>")
msgWindow.document.write("newWindow.location.pathname = " +
newWindow.location.pathname + "<P>")
msgWindow.document.write("newWindow.location.hash = " +
newWindow.location.hash + "<P>")
msgWindow.document.write("newWindow.location.search = " +
newWindow.location.search + "<P>")
msgWindow.document.close() The previous example displays output such as the following:

newWindow.location.href =
http://home.netscape.com/comprod/products/navigator/
version_2.0/script/script_info/objects.html#checkbox_object
newWindow.location.protocol = http:
newWindow.location.host = home.netscape.com
newWindow.location.hostName = home.netscape.com
newWindow.location.port =
newWindow.location.pathname =
/comprod/products/navigator/version_2.0/script/
script_info/objects.html
newWindow.location.hash = #checkbox_object
newWindow.location.search =

参看

Location.hash, Location.host, Location.hostname, Location.pathname, Location.port, Location.protocol, Location.search

pathname

A string specifying the URL-path portion of the URL.

属性源 | Location
实现版本 | Navigator 2.0

安全性

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

描述

The pathname property specifies a portion of the URL. The pathname supplies the details of how the specified resource can be accessed.

You can set the pathname property at any time, although it is safer to set the href property to change a location. If the pathname that you specify cannot be found in the current location, you get an error.

See Section 3.1 of RFC 1738 (http://www.cis.ohio-state.edu/htbin/rfc/rfc1738.html) for complete information about the pathname.

示例

In the following example, the window.open statement creates a window called newWindow and loads the specified URL into it. The document.write statements display properties of newWindow.location in a window called msgWindow.

newWindow=window.open
("http://home.netscape.com/comprod/products/navigator/
version_2.0/script/script_info/objects.html#checkbox_object") msgWindow.document.write("newWindow.location.href = " +
newWindow.location.href + "<P>")
msgWindow.document.write("newWindow.location.pathname = " +
newWindow.location.pathname + "<P>")
msgWindow.document.close() The previous example displays output such as the following:

newWindow.location.href =
http://home.netscape.com/comprod/products/navigator/
version_2.0/script/script_info/objects.html#checkbox_object
newWindow.location.pathname =
/comprod/products/navigator/version_2.0/script/
script_info/objects.html

参看

Location.hash, Location.host, Location.hostname, Location.href, Location.port, Location.protocol, Location.search

port

A string specifying the communications port that the server uses.

属性源 | Location
实现版本 | Navigator 2.0

安全性

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

描述

The port property specifies a portion of the URL. The port property is a substring of the hostname property. The hostname property is the concatenation of the host and port properties, separated by a colon.

You can set the port property at any time, although it is safer to set the href property to change a location. If the port that you specify cannot be found in the current location, you get an error. If the port property is not specified, it defaults to 80.

See Section 3.1 of RFC 1738 (http://www.cis.ohio-state.edu/htbin/rfc/rfc1738.html) for complete information about the port.

示例

In the following example, the window.open statement creates a window called newWindow and loads the specified URL into it. The document.write statements display properties of newWindow.location in a window called msgWindow.

newWindow=window.open
("http://home.netscape.com/comprod/products/navigator/
version_2.0/script/script_info/objects.html#checkbox_object") msgWindow.document.write("newWindow.location.href = " +
newWindow.location.href + "<P>")
msgWindow.document.write("newWindow.location.port = " +
newWindow.location.port + "<P>")
msgWindow.document.close() The previous example displays output such as the following:

newWindow.location.href =
http://home.netscape.com/comprod/products/navigator/
version_2.0/script/script_info/objects.html#checkbox_object
newWindow.location.port =

参看

Location.hash, Location.host, Location.hostname, Location.href, Location.pathname, Location.protocol, Location.search

protocol

A string specifying the beginning of the URL, up to and including the first colon.

属性源 | Location
实现版本 | Navigator 2.0

安全性

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

描述

The protocol property specifies a portion of the URL. The protocol indicates the access method of the URL. For example, the value "http:" specifies HyperText Transfer Protocol, and the value "javascript:" specifies JavaScript code.

You can set the protocol property at any time, although it is safer to set the href property to change a location. If the protocol that you specify cannot be found in the current location, you get an error.

The protocol property represents the scheme name of the URL. See Section 2.1 of RFC 1738 (http://www.cis.ohio-state.edu/htbin/rfc/rfc1738.html) for complete information about the protocol.

示例

In the following example, the window.open statement creates a window called newWindow and loads the specified URL into it. The document.write statements display properties of newWindow.location in a window called msgWindow.

newWindow=window.open
("http://home.netscape.com/comprod/products/navigator/
version_2.0/script/script_info/objects.html#checkbox_object") msgWindow.document.write("newWindow.location.href = " +
newWindow.location.href + "<P>")
msgWindow.document.write("newWindow.location.protocol = " +
newWindow.location.protocol + "<P>")
msgWindow.document.close() The previous example displays output such as the following:

newWindow.location.href =
http://home.netscape.com/comprod/products/navigator/
version_2.0/script/script_info/objects.html#checkbox_object
newWindow.location.protocol = http:

参看

Location.hash, Location.host, Location.hostname, Location.href, Location.pathname, Location.port, Location.search

search

A string beginning with a question mark that specifies any query information in the URL.

属性源 | Location
实现版本 | Navigator 2.0

安全性

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

描述

The search property specifies a portion of the URL. This property applies to HTTP URLs only.

The search property contains variable and value pairs; each pair is separated by an ampersand. For example, two pairs in a search string could look as follows:

?x=7&y=5 You can set the search property at any time, although it is safer to set the href property to change a location. If the search that you specify cannot be found in the current location, you get an error.

See Section 3.3 of RFC 1738 (http://www.cis.ohio-state.edu/htbin/rfc/rfc1738.html) for complete information about the search.

示例

In the following example, the window.open statement creates a window called newWindow and loads the specified URL into it. The document.write statements display properties of newWindow.location in a window called msgWindow.

newWindow=window.open
("http://guide-p.infoseek.com/WW/NS/Titles?qt=RFC+1738+&col=WW") msgWindow.document.write("newWindow.location.href = " +
newWindow.location.href + "<P>")
msgWindow.document.close()
msgWindow.document.write("newWindow.location.search = " +
newWindow.location.search + "<P>")
msgWindow.document.close() The previous example displays the following output:

newWindow.location.href =
http://guide-p.infoseek.com/WW/NS/Titles?qt=RFC+1738+&col=WW
newWindow.location.search = ?qt=RFC+1738+&col=WW

参看

Location.hash, Location.host, Location.hostname, Location.href, Location.pathname, Location.port, Location.protocol

方法

reload

 Forces a reload of the window's current document (the document specified by the Location.href property).

方法源 | Location
实现版本 | Navigator 3.0

语法

reload(forceGet)

参数

forceGet (Optional) If you supply true, forces an unconditional HTTP GET of the document from the server. This should not be used unless you have reason to believe that disk and memory caches are off or broken, or the server has a new version of the document (for example, if it is generated by a CGI on each request).

描述

This method uses the same policy that the browser's Reload button uses. The user interface for setting the default value of this policy varies for different browser versions.

By default, the reload method does not force a transaction with the server. However, if the user has set the preference to check every time, the method does a "conditional GET" request using an If-modified-since HTTP header, to ask the server to return the document only if its last-modified time is newer than the time the client keeps in its cache. In other words, reload reloads from the cache, unless the user has specified to check every time and the document has changed on the server since it was last loaded and saved in the cache.

示例

The following example displays an image and three radio buttons. The user can click the radio buttons to choose which image is displayed. Clicking another button lets the user reload the document.

<SCRIPT>
function displayImage(theImage) {
document.images[0].src=theImage
}
</SCRIPT>
<FORM NAME="imageForm">
<B>Choose an image:</B>
<BR><INPUT TYPE="radio" NAME="imageChoice" VALUE="image1" CHECKED
onClick="displayImage('seaotter.gif')">Sea otter
<BR><INPUT TYPE="radio" NAME="imageChoice" VALUE="image2"
onClick="displayImage('orca.gif')">Killer whale
<BR><INPUT TYPE="radio" NAME="imageChoice" VALUE="image3"
onClick="displayImage('humpback.gif')">Humpback whale
<BR>
<IMG NAME="marineMammal" SRC="seaotter.gif" ALIGN="left" VSPACE="10">
<P><INPUT TYPE="button" VALUE="Click here to reload"
onClick="window.location.reload()">
</FORM>

参看

Location.replace

replace

Loads the specified URL over the current history entry.

方法源 | Location
实现版本 | Navigator 3.0

语法

replace("URL")

参数

URL Specifies the URL to load.

描述

The replace method loads the specified URL over the current history entry. After calling the replace method, the user cannot navigate to the previous URL by using browser's Back button.

If your program will be run with JavaScript in Navigator 2.0, you could put the following line in a SCRIPT tag early in your program. This emulates replace, which was introduced in Navigator 3.0:

if (location.replace == null)
location.replace = location.assign The replace method does not create a new entry in the history list. To create an entry in the history list while loading a URL, use the History.go method.

示例

The following example lets the user choose among several catalogs to display. The example displays two sets of radio buttons which let the user choose a season and a category, for example the Spring/Summer Clothing catalog or the Fall/Winter Home & Garden catalog. When the user clicks the Go button, the displayCatalog function executes the replace method, replacing the current URL with the URL appropriate for the catalog the user has chosen. After invoking displayCatalog, the user cannot navigate to the previous URL (the list of catalogs) by using browser's Back button.

<SCRIPT>
function displayCatalog() {
var seaName=""
var catName=""
   for (var i=0; i < document.catalogForm.season.length; i++) {
if (document.catalogForm.season[i].checked) {
seaName=document.catalogForm.season[i].value
i=document.catalogForm.season.length
}
}
   for (var i in document.catalogForm.category) {
if (document.catalogForm.category[i].checked) {
catName=document.catalogForm.category[i].value
i=document.catalogForm.category.length
}
}
fileName=seaName + catName + ".html"
location.replace(fileName)
}
</SCRIPT>
<FORM NAME="catalogForm">
<B>Which catalog do you want to see?</B>
<P><B>Season</B>
<BR><INPUT TYPE="radio" NAME="season" VALUE="q1" CHECKED>Spring/Summer
<BR><INPUT TYPE="radio" NAME="season" VALUE="q3">Fall/Winter
<P><B>Category</B>
<BR><INPUT TYPE="radio" NAME="category" VALUE="clo" CHECKED>Clothing
<BR><INPUT TYPE="radio" NAME="category" VALUE="lin">Linens
<BR><INPUT TYPE="radio" NAME="category" VALUE="hom">Home & Garden
<P><INPUT TYPE="button" VALUE="Go" onClick="displayCatalog()">
</FORM>

参看

History, Window.open, History.go, Location.reload


JavaScript语言参考手册_窗口

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

History

 Contains an array of information on the URLs that the client has visited within a window. This information is stored in a history list and is accessible through the browser's Go menu.

客户端对象 |
实现版本 | Navigator 2.0 Navigator 3.0: 添加了 current, next, and previous properties;

创建源

History objects are predefined JavaScript objects that you access through the history property of a Window object.

描述

To change a window's current URL without generating a history entry, you can use the Location.replace method. This replaces the current page with a new one without generating a history entry. See Location.replace.

You can refer to the history entries by using the Window.history array. This array contains an entry for each history entry in source order. Each array entry is a string containing a URL. For example, if the history list contains three named entries, these entries are reflected as history[0], history[1], and history[2].

If you access the history array without specifying an array element, the browser returns a string of HTML which displays a 表 of URLs, each of which is a link.

属性概览

current | Specifies the URL of the current history entry.
length | Reflects the number of entries in the history list.
next | Specifies the URL of the next history entry.
previous | Specifies the URL of the previous history entry.

方法概览

back | Loads the previous URL in the history list.
forward | Loads the next URL in the history list.
go | Loads a URL from the history list.

示例

示例 1. The following example goes to the URL the user visited three clicks ago in the current window.

history.go(-3) 示例 2. You can use the history object with a specific window or frame. The following example causes window2 to go back one item in its window (or session) history:

window2.history.back() 示例 3. The following example causes the second frame in a frameset to go back one item:

parent.frames[1].history.back() 示例 4. The following example causes the frame named frame1 in a frameset to go back one item:

parent.frame1.history.back() 示例 5. The following example causes the frame named frame2 in window2 to go back one item:

window2.frame2.history.back() 示例 6. The following code determines whether the first entry in the history array contains the string "NETSCAPE". If it does, the function myFunction is called.

if (history[0].indexOf("NETSCAPE") != -1) {
myFunction(history[0])
}
示例 7. The following example displays the entire history list:

document.writeln("<B>history is</B> " + history) This code displays output similar to the following:

history is
Welcome to Netscape http://home.netscape.com/
Sun Microsystems http://www.sun.com/
Royal Airways http://www.supernet.net/~dugbrown/

参看

Location, Location.replace

属性

current

 A string specifying the complete URL of the current history entry.

属性源 | History
只读 |
实现版本 | Navigator 3.0

安全性

Navigator 3.0: This property is tainted by default. It has no value of data tainting is disabled. For information on data tainting, see "JavaScript Security".

Navigator 4.0: Getting the value of this property requires the UniversalBrowserRead privilege. It has no value if you do not have this privilege. 要获取 Navigator 4.0 中关于安全性更多的信息，请看“JavaScript 指南”中的第七章“JavaScript 安全性”。

示例

The following example determines whether history.current contains the string "netscape.com". If it does, the function myFunction is called.

if (history.current.indexOf("netscape.com") != -1) {
myFunction(history.current)
}

参看

History.next, History.previous

length

The number of elements in the history array.

属性源 | History
只读 |
实现版本 | Navigator 2.0

安全性

Navigator 4.0: Getting the value of this property requires the UniversalBrowserRead privilege. 要获取 Navigator 4.0 中关于安全性更多的信息，请看“JavaScript 指南”中的第七章“JavaScript 安全性”。

next

A string specifying the complete URL of the next history entry.

属性源 | History
只读 |
实现版本 | Navigator 3.0

安全性

Navigator 3.0: This property is tainted by default. It has no value of data tainting is disabled. For information on data tainting, see "JavaScript Security".

Navigator 4.0: Getting the value of this property requires the UniversalBrowserRead privilege. It has no value if you do not have this privilege. 要获取 Navigator 4.0 中关于安全性更多的信息，请看“JavaScript 指南”中的第七章“JavaScript 安全性”。

描述

The next property reflects the URL that would be used if the user chose Forward from the Go menu.

示例

The following example determines whether history.next contains the string "NETSCAPE.COM". If it does, the function myFunction is called.

if (history.next.indexOf("NETSCAPE.COM") != -1) {
myFunction(history.next)
}

参看

History.current, History.previous

previous

A string specifying the complete URL of the previous history entry.

属性源 | History
只读 |
实现版本 | Navigator 3.0

安全性

Navigator 3.0: This property is tainted by default. It has no value of data tainting is disabled. For information on data tainting, see "JavaScript Security".

Navigator 4.0: Getting the value of this property requires the UniversalBrowserRead privilege. It has no value if you do not have this privilege. 要获取 Navigator 4.0 中关于安全性更多的信息，请看“JavaScript 指南”中的第七章“JavaScript 安全性”。

描述

The previous property reflects the URL that would be used if the user chose Back from the Go menu.

示例

The following example determines whether history.previous contains the string "NETSCAPE.COM". If it does, the function myFunction is called.

if (history.previous.indexOf("NETSCAPE.COM") != -1) {
myFunction(history.previous)
}

参看

History.current, History.next

方法

back

 Loads the previous URL in the history list.

方法源 | History
实现版本 | Navigator 2.0

语法

back()

参数

 无

描述

This method performs the same action as a user choosing the Back button in the browser. The back method is the same as history.go(-1).

示例

The following custom buttons perform the same operation as the browser's Back button:

<P><INPUT TYPE="button" VALUE="< Go Back"
onClick="history.back()">
<P><INPUT TYPE="button" VALUE="> Go Back"
onClick="myWindow.back()">

参看

History.forward, History.go

forward

Loads the next URL in the history list.

方法源 | History
实现版本 | Navigator 2.0

语法

forward()

参数

 无

描述

This method performs the same action as a user choosing the Forward button in the browser. The forward method is the same as history.go(1).

示例

The following custom buttons perform the same operation as the browser's Forward button:

<P><INPUT TYPE="button" VALUE="< Forward"
onClick="history.forward()">
<P><INPUT TYPE="button" VALUE="> Forward"
onClick="myWindow.forward()">

参看

History.back, History.go

go

Loads a URL from the history list.

方法源 | History
实现版本 | Navigator 2.0

语法

go(delta)
go(location)

参数

delta | An integer representing a relative position in the history list.
location | A string representing all or part of a URL in the history list.

描述

The go method navigates to the location in the history list determined by the specified parameter.

If the delta argument is 0, the browser reloads the current page. If it is an integer greater than 0, the go method loads the URL that is that number of entries forward in the history list; otherwise, it loads the URL that is that number of entries backward in the history list.

The location argument is a string. Use location to load the nearest history entry whose URL contains location as a substring. Matching the URL to the location parameter is case-insensitive. Each section of a URL contains different information. See Location for a描述 of the URL components.

The go method creates a new entry in the history list. To load a URL without creating an entry in the history list, use Location.replace.

示例

The following button navigates to the nearest history entry that contains the string "home.netscape.com":

<P><INPUT TYPE="button" VALUE="Go"
onClick="history.go('home.netscape.com')"> The following button navigates to the URL that is three entries backward in the history list:

<P><INPUT TYPE="button" VALUE="Go"
onClick="history.go(-3)">

参看

History.back, History.forward, Location.reload, Location.replace


JavaScript语言参考手册_窗口

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

screen

 包含了描述显示屏幕和颜色的属性。

客户端对象 |
实现版本 | Navigator 4.0

创建源

The JavaScript runtime engine creates the screen object for you. You can access its properties automatically.

描述

该对象包含了允许你获取关于用户显示情况信息的只读属性。

属性概览

availHeight | 以像素为单位指定了屏幕的高度，minus permanent or semipermanent user interface features displayed by the operating system, such as the Taskbar on Windows.
availWidth | Specifies the width of the screen, in pixels, minus permanent or semipermanent user interface features displayed by the operating system, such as the Taskbar on Windows.
colorDepth | The bit depth of the color palette, if one is in use; otherwise, the value is derived from screen.pixelDepth.
height | Display screen height.
pixelDepth | Display screen color resolution (bits per pixel).
width | Display screen width.

示例

The following function creates a string containing the current display properties:

function screen_properties() {
document.examples.results.value = "("+screen.width+" x
"+screen.height+") pixels, "+
screen.pixelDepth +" bit depth, "+
screen.colorDepth +" bit color palette depth.";
} // end function screen_properties

属性

availHeight

 Specifies the height of the screen, in pixels, minus permanent or semipermanent user interface features displayed by the operating system, such as the Taskbar on Windows.

属性源 | screen
实现版本 | Navigator 4.0

availWidth

Specifies the width of the screen, in pixels, minus permanent or semipermanent user interface features displayed by the operating system, such as the Taskbar on Windows.

属性源 | screen
实现版本 | Navigator 4.0

colorDepth

The bit depth of the color palette in bits per pixel, if a color palette is in use. Otherwise, this property is derived from screen.pixelDepth.

属性源 | screen
实现版本 | Navigator 4.0

height

Display screen height, in pixels.

属性源 | screen
实现版本 | Navigator 4.0

pixelDepth

Display screen color resolution, in bits per pixel.

属性源 | screen
实现版本 | Navigator 4.0

width

Display screen width, in pixels.

属性源 | screen
实现版本 | Navigator 4.0

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