【JS】我的JavaScript学习之路(2)

3.从JavaScript页面解析过程看执行顺序

代码(test.html):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <title>ch1_example2</title>
    </head>
    <body bgcolor="WHITE">
        <p>Paragraph 1</p>
        <script type="text/javascript" language="JavaScript">
            // Script block 1
            alert("First Script Block");
        </script>
        <p>Paragraph 2</p>
        <script type="text/javascript" language="JavaScript">
            // Script block 2
            document.bgColor = "RED";
            alert("Second Script Block");
        </script>
        <p>Paragraph 3</p>
    </body>
</html>

执行后是这个样子滴。

第一步:

1

第二步:

2

第三步:

3

由此看出,页面解析是自上而下执行的,没有异步,在提示框弹出时,页面是暂停的,而没有去后台执行。

 

4.用JavaScript将信息写在网页上
接下来我们仅仅使用JavaScript来将“Hello World!”写入空白页面

代码(test2.html):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

        <title>ch1_example3</title>

    </head>

    <body>
        <p id="ResultP"></p>
        <script type="text/javascript" language="JavaScript">
            // Script block 1
            document.getElementById('ResultP').innerHTML = 'Hello World';
        </script>
    </body>
</html>

在此页中,我们使用<p id="ResultP"></p> 创建了一个id是"ResultP"的段落。为标签创建ID,可以方便我们在页面中找到它,也可以使我们在使用CSS时对特殊的标签进行单独的设计。

在创建段落之后,我们通过<script></script>引入JavaScript语句:

document.getElementById('ResultP') 可以获取到这个id是"ResultP"的段落。

然后再通过innerHTML属性,来更改段落中的文字为“Hello World!”

这样我们就可以获得一个形似<p>Hello World!</p>标签的效果了,我们就可以在页面上输出“Hello World!”

posted @ 2012-08-14 22:54  Ternence Lin  阅读(159)  评论(0编辑  收藏  举报