文字
分享


在浏览器中显示信息

Microsoft JScript 提供了两种方式来在浏览器中直接显示数据。可以使用write( )writeln( ),这两个函数是document 对象的方法。也可以在浏览器中以表格的方式显示信息,以及用 警告、提示和确认 消息框来显示信息。

使用document.write( ) 和 document.writeln( )

显示信息最常用的方式是 document 对象的 write( ) 方法。该方法用一个字符串作为其参数,并在浏览器中显示。该字符串可以是普通文本或 HTML。

字符串可以用单引号或双引号引起来。这样可以引用那些包含引号或撇号的内容。

1

2

<code>document.write("Pi is approximately equal to " + Math.PI);

document.write( );</code>

注意   下面的简单函数可以避免在浏览器中显示信息时不得不键入 "document.write"。该函数不能告知要显示的信息是否未定义,而是发布给命令 "w();",该命令将显示一个空行。

1

2

3

4

5

6

7

8

9

10

11

12

<code>function w(m) { // </code>编写函数。

<code>m = "" + m + ""; //  </code>确保变量<code> m </code>是一个字符串。

<code>if ("undefined" != m) { // </code>判别是否为空或其它未定义的项。

   <code>document.write(m);</code>

<code>   }</code>

<code>document.write("<br>");</code>

<code>}</code>

 

<code>w('<IMG SRC="horse.gif">');</code>

<code>w();</code>

<code>w("This is an engraving of a horse.");</code>

<code>w();</code>

writeln( ) 方法与 write( ) 方法几乎一样,差别仅在于是前者将在所提供的任何字符串后添加一个换行符。在 HTML 中,这通常只会在后面产生一个空格;不过如果使用了 <PRE> 和 <XMP> 标识,这个换行符会被解释,且在浏览器中显示。

在调用 write( ) 方法时,如果该文档不处于在调用 write( ) 方法时的打开和分析的过程中,该方法将打开并清除该文档,所以它可能是有危险的。该示例显示了一个每隔一分钟就显示时间的脚本,但是在第一次显示后由于它从过程中将自己清除,因此会导致失败。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

<code><HTML>

<HEAD>

<SCRIPT LANGUAGE="JScript">

function singOut()  {

var theMoment = new Date();

var theHour = theMoment.getHours();

var theMinute = theMoment.getMinutes();

var theDisplacement = (theMoment.getTimezoneOffset() / 60);

theHour -= theDisplacement;

if (theHour > 23)  {

theHour -= 24

}

document.write(theHour + " hours, " + theMinute + " minutes, Coordinated Universal Time.");

window.setTimeout("singOut();", 60000);

}

</SCRIPT>

</HEAD>

<BODY>

<SCRIPT>

singOut();

</SCRIPT>

</BODY>

</HTML></code>

如果使用 window 对象的 alert() 方法而不是 document.write(),则该脚本可以运行。

1

2

3

<code>window.alert(theHour + " hours, " + theMinute + " minutes, Coordinated Universal Time.");

window.setTimeout("singOut();", 60000);

</code>}

清除当前文档

document 对象的 clear() 方法将清空当前文档。该方法也将清除您的脚本(随文档的其他部分一起),因此要特别注意该方法的使用方式及在什么时候使用该方法。

1

<code>document.clear();</code>

上一篇:条件编译变量下一篇:使用消息框