深入浅出JavaScript笔记

JavaScript块一般放在Html中的<head>中,这算是个好习惯吧。

通常我们提交表单,都需要在后台做一些校验,一般有两种方式,提交到服务器后由服务器校验,另外一种就是提交表单到服务器前,由浏览器先做校验。后者指的就是使用JavaScript等做校验,这种方式的好处是减轻服务器的负担,并且缩短响应时间,因为JavaScript无需刷新页面就可以实现和用户交互。

 

 

案例:iRock宠物。

<html>

  <head>

    <title>iRock - The Virtual Pet Rock</title>

 

    <script type="text/javascript">

      function touchRock() {

        var userName = prompt("What is your name?", "Enter your name here.");

        if (userName) {

          alert("It is good to meet you, " + userName + ".");

          document.getElementById("rockImg").src = "rock_happy.png";

        }

      }

    </script>

  </head>

 

  <bodyonload="alert('Hello, I\'m your pet rock.');">

    <div style="margin-top:100px; text-align:center">

      <img id="rockImg" src="rock.png" alt="iRock" style="cursor:pointer" onclick="touchRock();" />

    </div>

  </body>

</html>

      

上面例子,是一个宠物石头,打开网页就会弹出一句欢迎,然后点击图片会变成笑脸。

       之所以打开网页会弹出欢迎,是因为在body标签里有onload属性,该属性后面可以加多个函数,其中alert的JavaScript的内置函数,除了在body标签中加onload属性外,还可以直接写一段JavaScript代码实现打开网页时候就执行的函数,如下:

      window.onload=function(){

        alert("Hello, I\'m your pet rock.");

      }

       如果windons.onload和body标签也有onload属性,那么windows.onload会被屏蔽掉。

 

 

       JavaScript中有变量和常量两种,创建的关键字分别是:var,const。定义常量,建议在创建的时候就初始化其值。

       特殊值:NaN(not a number),表示非数字。一般出现在数字与非数字(如字符串)的乘除等运算中出现的结果。此外,JS中有一函数用于判断是否为非数字:isNaN()。

       JavaScript中,使用document对象获取页面对话框的值,返回的都是字符型,所以如果想进行数学运算,那么首先需要转型,JS提供的两个转换函数是:parseInt()、parseFloat()。

 

案例:甜甜圈预订。

<html>

  <head>

    <title>Duncan's Just-In-Time Donuts</title>

 

    <link rel="stylesheet" type="text/css" href="donuts.css" />

 

    <script type="text/javascript">

      function updateOrder() {

        const TAXRATE = 0.0925;

        const DONUTPRICE = 0.50;

        var numCakeDonuts = parseDonuts(document.getElementById("cakedonuts").value);

        var numGlazedDonuts = parseDonuts(document.getElementById("glazeddonuts").value);

        if (isNaN(numCakeDonuts)){

          numCakeDonuts = 0;

       }

        if (isNaN(numGlazedDonuts)){

          numGlazedDonuts = 0;

       }

        var subTotal = (numCakeDonuts + numGlazedDonuts) * DONUTPRICE;

        var tax = subTotal * TAXRATE;

        var total = subTotal + tax;

        document.getElementById("subtotal").value = "$" + subTotal.toFixed(2);

        document.getElementById("tax").value = "$" + tax.toFixed(2);

        document.getElementById("total").value = "$" + total.toFixed(2);

      }

 

      function parseDonuts(donutString) {

        numDonuts = parseInt(donutString);

        if (donutString.indexOf("dozen") != -1){

          numDonuts *= 12;

       }

        return numDonuts;

      }

 

      function placeOrder(form) {

        if (document.getElementById("name").value == ""){

          alert("I'm sorry but you must provide your name before submitting an order.");

       } else if (document.getElementById("pickupminutes").value == "" ||

          isNaN(document.getElementById("pickupminutes").value)){

              alert("I'm sorry but you must provide the number of minutes until pick-up before submitting an order.");

         } else{

              // Submit the order to the server

              form.submit();

         }

      }

    </script>

  </head>

 

  <body>

    <div id="frame">

      <div class="heading">Duncan's Just-In-Time Donuts</div>

      <div class="subheading">All donuts 50 cents each, cake or glazed!</div>

      <div id="left">

        <img src="donuttime.png" alt="Just-In-Time Donuts" />

      </div>

      <form name="orderform" action="donuts.php" method="POST">

        <div class="field">

          Name: <input type="text" id="name" name="name" value="" />

        </div>

        <div class="field">

        # of cake donuts: <input type="text" id="cakedonuts" name="cakedonuts" value=""

          onchange="updateOrder();" />

        </div>

        <div class="field">

        # of glazed donuts: <input type="text" id="glazeddonuts" name="glazeddonuts" value=""

          onchange="updateOrder();" />

        </div>

        <div class="field">

        Minutes 'til pickup: <input type="text" id="pickupminutes" name="pickupminutes" value="" />

        </div>

        <div class="field">

        Subtotal: <input type="text" id="subtotal" name="subtotal" value="" readonly="readonly" />

        </div>

        <div class="field">

        Tax: <input type="text" id="tax" name="tax" value="" readonly="readonly" />

        </div>

        <div class="field">

        Total: <input type="text" id="total" name="total" value="" readonly="readonly" />

        </div>

        <div class="field">

        <input type="button" value="Place Order" onclick="placeOrder(this.form);" />

        </div>

      </form>

    </div>

  </body>

</html>

       上面在placeOrder(form)函数中,传入的是一个form对象,所以在JavaScript代码中,就可以使用submit( )方法。

 

       在JS中,有设定时间的内置函数:

l  达到指定时间时执行:setTimeout( Timer code,  Timerdelay );

l  每间隔一段时间就执行:setInterval( Timer code,  Timerdelay );

其中,Timer code:定时器终止时运行的代码;Timer delay:时间语句,以毫秒为计算单位。

       如果我们想终止一个计时器,则可以分别使用以下内置函数,timerID表示计时器的id值:

l  用于清除单次定时器:clearTimeout(timerID);

l  用于清除间隔定时器:clearInterval(timerID);

 

范例:完善iRock页面。

<html>

  <head>

    <title>iRock - The Virtual Pet Rock</title>

 

    <script type="text/javascript" src="cookie.js"></script>

 

    <script type="text/javascript">

      var userName;

 

      function resizeRock() {

        document.getElementById("rockImg").style.height = (document.body.clientHeight - 100) * 0.9;

      }

 

      function greetUser() {

        if (navigator.cookieEnabled)

          userName = readCookie("irock_username");

        if (userName)

          alert("Hello " + userName + ", I missed you.");

        else

          alert('Hello, I am your pet rock.');

      }

 

      function touchRock() {

        if (userName) {

          alert("I like the attention, " + userName + ". Thank you.");

        }

        else {

          userName = prompt("What is your name?", "Enter your name here.");

          if (userName) {

            alert("It is good to meet you, " + userName + ".");

            if (navigator.cookieEnabled)

              writeCookie("irock_username", userName, 5 * 365);

            else

              alert("Cookies aren't supported/enabled in your browser, which means I won't remember you later. I'm sorry.");

          }

        }

        document.getElementById("rockImg").src= "rock_happy.png";

        document.getElementById("rockImg").alt = "happy rock";

        setTimeout("document.getElementById('rockImg').src = 'rock.png';", 5 * 60 * 1000);

      }

    </script>

  </head>

 

  <body onload="resizeRock(); greetUser();" onresize="resizeRock();">

    <div style="margin-top:100px; text-align:center">

      <img id="rockImg" src="rock.png" alt="iRock" style="cursor:pointer" onclick="touchRock();" />

    </div>

  </body>

</html>

 

       我们来看看上面使用到的语法。首先看看简单的:document.getElementById("rockImg").src,这里表示取到image对象rockImg,当然修改它的属性src的值。在页面中,<img> 标签每出现一次,一个 Image 对象就会被创建

然后来研究一下复杂一点的:“document.getElementById("rockImg").style.height”,表示的是先取到image对象rockImg,然后在这个image对象中取得style对象,再修改style对象中的属性height的值。

       注:其实个人觉得这就想Java里,在一个类定义了一个成员属性,然后这个成员属性又有自己的成员方法,如下,使用Java来表示上面的关系,setter、getter这些就省略了。

public class Image {

    String alt;

    String scr;

    String height;

    String weight;

    Style style;

}

 

class Style{

    String background;

    String border;

    String display;

}

在JS中,可以使用documengt对象中的body.clientHeight /body.clientWeight来获取浏览器窗口的高度和宽度(不包括工具栏/滚动条)。如下:

var bodyHeight = document.body.clientHeight;

var bodyWeight = document.body.clientHeight;

       需要注意的是,在上面例子中获取到style对象,可以修改height和weight等属性的值,但是body.clientHeight值不能修改,只能读取。

顺便说一下,以上方法适合于html页面,但是在xhtml中,则不适用,因为在html中body是整个DOM的根,而在xhtml中document才是根,所以在xhtml中想要取得整个页面的值,需要这样写:

var bodyHeight = document.documentElement.clientHeight;

var bodyWeight = document.documentElement.clientHeight;

       除了这两种方法之外,还可以使用以下方法取得浏览器窗口的内部高/宽:

var bodyHeight = window.innerHeight;

var bodyWeight = window.innerWidth;

       所以可以使用下面一段JS代码,来兼容所有浏览器:

var w = window.innerWidth ||

document.documentElement.clientWidth ||

document.body.clientWidth;

                

var h = window.innerHeight ||

         document.documentElement.clientHeight ||

         document.body.clientHeight;

上面使用到的navigator,属于Browser对象,该对象包含有关浏览器的信息。除此之外,Browser对象还有:

l  Window对象:表示浏览器中打开的窗口;

l  Screen对象:包含有关客户端显示屏幕的信息;

l  History对象:包含用户(在浏览器窗口中)访问过的 URL;

l  Location对象:包含有关当前 URL 的信息,Location 对象是 Window 对象的一个部分,可通过 window.location 属性来访问。

如果一段JavaScript代码的需要复用,那么我们可以将其抠出来,定义在后缀名为js的文档中,在页面中引入此文档,可以通过script标签的src属性来实现,上面例子就引入了以下js文档:

function writeCookie(name, value, days) {

  // By default, there is no expiration so the cookie is temporary

  var expires = "";

 

  // Specifying a number of days makes the cookie persistent

  if (days) {

    var date = new Date();

    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));

    expires = "; expires=" + date.toGMTString();

  }

 

  // Set the cookie to the name, value, and expiration date

  document.cookie = name + "=" + value + expires + "; path=/";

}

 

function readCookie(name) {

  // Find the specified cookie and return its value

  var searchName = name + "=";

  var cookies = document.cookie.split(';');

  for(var i=0; i < cookies.length; i++) {

    var c = cookies[i];

    while (c.charAt(0) == ' ')

      c = c.substring(1, c.length);

    if (c.indexOf(searchName) == 0)

      return c.substring(searchName.length, c.length);

  }

  return null;

}

 

function eraseCookie(name) {

  // Erase the specified cookie

  writeCookie(name, "", -1);

}

 

上面的Date,属于JS对象。toGMTString()是Date对象中的一个方法,表示:根据格林威治时间 (GMT) 把 Date 对象转换为字符串,并返回结果。但是w3c标准中不建议使用此方法,建议使用 toUTCString() 方法代替。

小结一下,在这之前我们通过document对象的getElementById()方法取得了不同的对象,进而对不同对象的属性进行修改,或者调用对象的方法(例如,调用form对象的submit()方法)。所以我们在获取对象的时候,需要明确所获取到的是什么对象,然后才能进行对该对象所拥有的属性进行修改。

 

 

 

之所以说JS是四不像,对象使用混乱

 

 

 

 

onclick属于事件,与click()方法不同,不要混淆

document.getElementById(“id”).οnclick= function(evt){ };这里的onclick属于HTML事件,大多数DOM对象都有onclick事件,如input标签相关的对象,image对象。简单来说,onclick事件指的是鼠标点击一下。

而click()方法就是指“单击”,如按钮、radio、checkbox这些对象,按钮的click()方法即按钮被点击一下,而radio和checkbox的click()方法即表示被选中。

范例:使用click()方法。

<html>

    <head>

        <script type="text/javascript">

            function clickRadio(){

                document.getElementById('radio1').click()

            }

        </script>

    </head>

    <body>

        <form>

            <input type="radio" id="radio1" />

            <br/>

            <input type="button" onclick="clickRadio()" value="Click radio button" />

        </form>

    </body>

</html>

       如上所示,如果点击一下按钮,radio单选框就会被选中,因为触发了radio对象的click()方法。当然我们也可以为image等对象触发click()方法,但是该对象中应该为onclick事件添加函数,否则没有意义。

范例:对image对象使用click()方法。

<html>

    <head>

        <script type="text/javascript">

            var status = 1;

            function clickButton(){

                document.getElementById('seat').click();

            }

            function changeColor(){

              if(status==1){

                  document.getElementById("seat").src="pic/seat_green.png";

                  status = 2;

              }else if(status==2){

                  document.getElementById("seat").src="pic/seat_red.png";

                  status = 1;

              }

            }

        </script>

    </head>

    <body>

        <form>

           <img id="seat" src="pic/seat_red.png" onclick="changeColor()" /> <br />

            <input type="button" id="button1" onclick="clickButton()" value="Change color" />

        </form>

    </body>

</html>

          

       上面的按钮点击一下,座椅就会变色。代码执行过程是:

按钮触发了按钮对象的onclick事件 → 触发图片的click()方法 → 触发image对象的onclick事件。

上面的代码只是为了说明语法,实际开发中并不会大费周章来这样改变图片,开发中一般这样写:

<html>

    <head>

        <script type="text/javascript">

            var status = 1;

            function changeColor(){

                if (status == 1) {

                    document.getElementById("seat").src = "pic/seat_green.png";

                    status = 2;

                }

                else

                    if (status == 2) {

                        document.getElementById("seat").src = "pic/seat_red.png";

                        status = 1;

                    }

            }

            var changeColorRef = changeColor;            

            window.onload = function(){

                document.getElementById("seat").onclick=changeColorRef;

                document.getElementById("button1").onclick = changeColor;

            };

        </script>

    </head>

    <body>

        <form>

            <img id="seat" src="pic/seat_red.png"/>

            <br/>

            <input type="button" id="button1" value="Change color"/>

        </form>

    </body>

</html>

       上面的window.onload表示在网页加载前就执行的,与<body>标签中的onload事件一样,不过这样可以避免在 <body >标签中的onload事件里写多个函数了,因为你现在可以这样写了:

window.οnlοad=function(){  func1();  func2(); …… }

       上面的“function(){…}”表示的是一个匿名函数,由于没有函数名,所以也决定了其只能被调用一次。当然你也可以使用函数引用,观察以下这行代码:

       varchangeColorRef = changeColor;

       这里使用的就是函数引用,可以理解为将changeColorRef变量的指针指向changeColor函数,其实也相当于给函数起个别名。所以也可以怎样来创建一个函数:

    var changeColorRef = function(){

       //some codes

    }

       下面我们就可以在onclick事件中使用函数引用了:

       document.getElementById("seat").οnclick= changeColorRef;

       当然,函数名本身也可以直接这样使用,效果一样,如下:

       document.getElementById("seat").οnclick= changeColor;

       “.onclick”表示触发鼠标单击事件,后面接的函数不需要带括号,切记!其实只需要记住一点:在函数引用的时候不能加括号,在调用函数的时候才需要。因为调用函数表示此函数需要立刻执行,我们之前在标签里使用的就是调用函数,表示的是标签里指定的事件一触发,那么就立刻执行所调用的函数。上面这些,如“window.οnlοad=functionName”、“document.getElementBy(ID).οnclick=functionName”就属于回调函数。回调函数指被浏览器调用,以响应发生在你脚本外的事情。使用回调函数可以很好的与html代码相分离,可以说是“解耦合”。

 

小结:

window对象方法可以直接调用,如alert()、close()、等等,待测试!!

 

调用函数(calling a function)、回调函数(callback function),暂时只有用于事件处理器,当然以后会学到Ajax。

 

onload事件处理器中一般使用匿名函数(函数字面量),而不是函数引用(functionreference),因为onload事件处理器只执行一次,其函数一般也不会被复用。

 

 

 

 

正则表达式

范例:下面例子包含了大部分正则的内容。

<html>

  <head>

    <title>Bannerocity - Personalized Online Sky Banners</title>

 

    <link rel="stylesheet" type="text/css" href="bannerocity.css" />

 

    <script type="text/javascript">

      function validateRegEx(regex, input, helpText, helpMessage) {

        // See if the input data validates OK

        if (!regex.test(input)) {

          // The data is invalid, so set the help message and return false

          if (helpText != null)

            helpText.innerHTML = helpMessage;

          return false;

        }

        else {

          // The data is OK, so clear the help message and return true

          if (helpText != null)

            helpText.innerHTML = "";

          return true;

        }

      }

 

      function validateNonEmpty(inputField, helpText) {

        // See if the input value contains any text

        return validateRegEx(/.+/,

          inputField.value, helpText,

          "Please enter a value.");

      }

 

      function validateLength(minLength, maxLength, inputField, helpText) {

        // See if the input value contains at least minLength but no more than maxLength characters

        return validateRegEx(new RegExp("^.{" + minLength + "," + maxLength + "}$"),

          inputField.value, helpText,

          "Please enter a value " + minLength + " to " + maxLength +

          " characters in length.");

      }

 

      function validateZipCode(inputField, helpText) {

        // First see if the input value contains data

        if (!validateNonEmpty(inputField, helpText))

          return false;

 

        // Then see if the input value is a ZIP code

        return validateRegEx(/^\d{5}$/,

          inputField.value, helpText,

          "Please enter a 5-digit ZIP code.");

      }

 

      function validateDate(inputField, helpText) {

        // First see if the input value contains data

        if (!validateNonEmpty(inputField, helpText))

          return false;

 

        // Then see if the input value is a date

        return validateRegEx(/^\d{2}\/\d{2}\/(\d{2}|\d{4})$/,

          inputField.value, helpText,

          "Please enter a date (for example, 01/14/1975).");

      }

 

      function validatePhone(inputField, helpText) {

        // First see if the input value contains data

        if (!validateNonEmpty(inputField, helpText))

          return false;

 

        // Then see if the input value is a phone number

        return validateRegEx(/^\d{3}-\d{3}-\d{4}$/,

          inputField.value, helpText,

          "Please enter a phone number (for example, 123-456-7890).");

      }

 

      function validateEmail(inputField, helpText) {

        // First see if the input value contains data

        if (!validateNonEmpty(inputField, helpText))

          return false;

 

        // Then see if the input value is an email address

        return validateRegEx(/^[\w\.-\+]+@[\w-]+(\.\w{2,3})+$/,

          inputField.value, helpText,

          "Please enter an email address (for example, johndoe@acme.com).");

      }

 

      function placeOrder(form) {

        if (validateLength(1, 32, form["message"], form["message_help"]) &&

          validateZipCode(form["zipcode"], form["zipcode_help"]) &&

          validateDate(form["date"], form["date_help"]) &&

          validateNonEmpty(form["name"], form["name_help"]) &&

          validatePhone(form["phone"], form["phone_help"]) &&

          validateEmail(form["email"], form["email_help"])) {

          // Submit the order to the server

          form.submit();

        } else {

          alert("I'm sorry but there is something wrong with the order information.");

        }

      }

    </script>

  </head>

 

  <body onload="document.getElementById('message').focus()">

    <div class="heading">

      <img id="logo" src="logo.png" alt="Bannerocity" />

    </div>

 

    <form name="orderform" action="bannerocity.php" method="POST">

      <div class="field">

        Enter the banner message:

        <input id="message" name="message" type="text" size="32"

          onblur="validateLength(1, 32, this, document.getElementById('message_help'))" />

        <span id="message_help" class="help"></span>

      </div>

      <div class="field">

        Enter ZIP code of the location:

        <input id="zipcode" name="zipcode" type="text" size="5"

          onblur="validateZipCode(this, document.getElementById('zipcode_help'))" />

        <span id="zipcode_help" class="help"></span>

      </div>

      <div class="field">

        Enter the date for the message to be shown:

        <input id="date" name="date" type="text" size="10"

          onblur="validateDate(this, document.getElementById('date_help'))" />

        <span id="date_help" class="help"></span>

      </div>

      <div class="field">

        Enter your name:

        <input id="name" name="name" type="text" size="32"

          onblur="validateNonEmpty(this, document.getElementById('name_help'))" />

        <span id="name_help" class="help"></span>

      </div>

      <div class="field">

        Enter your phone number:

        <input id="phone" name="phone" type="text" size="12"

          onblur="validatePhone(this, document.getElementById('phone_help'))" />

        <span id="phone_help" class="help"></span>

      </div>

      <div class="field">

        Enter your email address:

        <input id="email" name="email" type="text" size="32"

          onblur="validateEmail(this, document.getElementById('email_help'))" />

        <span id="email_help" class="help"></span>

      </div>

      <input type="button" value="Order Banner" onclick="placeOrder(this.form);" />

    </form>

  </body>

</html>

特别留意email的正则表达式,了解中括号[ ]与小括号( )的使用。上面调用form表单中的对象引出了另一种用法:formName[ID],这种写法与之前的getElementById(ID)一样。不过一般开发中数据都会包含在一个form表单中,所以使用formName[ID]这种方法更加方便。

对于正则表达式,常用的有以下这些:

1、验证由数字、26个英文字母或者下划线组成的字符串:^\w+$ 

2、验证由数字和26个英文字母组成的字符串:^[A-Za-z0-9]+$ 

3、  验证用户密码:^[a-zA-Z]\w{5,17}$正确格式为:以字母开头,长度在6-18之间,只能包含字符、数字和下划线。

4、 验证汉字:^[\u4e00-\u9fa5],{0,}$ 

5、 验证Email地址:^\w+[-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$ 

6、 整数:^-?\d+$ 

7、 非负浮点数(正浮点数 + 0):^\d+(\.\d+)?$ 

8、 验证有两位小数的正实数:^[0-9]+(.[0-9]{2})?$ 

9、  验证长度为3的字符:^.{3}$ 

 

 

 

范例:火柴人冒险记完善。

<html>

  <head>

    <title>Stick Figure Adventure</title>

 

    <style type="text/css">

      span.decision {

        font-weight:bold;

        border:thin solid #000000;

        padding:5px;

        background-color:#DDDDDD;

      }

 

      span.decisionhover {

        font-weight:bold;

        border:thin solid #000000;

        padding:5px;

        background-color:#EEEEEE;

      }

    </style>

 

    <script type="text/javascript">

      // Initialize the current scene to Scene 0 (Intro)

      var curScene = 0;

 

      function replaceNodeText(id, newText) {

        var node = document.getElementById(id);

        while (node.firstChild)

          node.removeChild(node.firstChild);

        node.appendChild(document.createTextNode(newText));

      }

 

      function changeScene(decision) {

        // Clear the scene message

        var message = "";

        var decision1 = "", decision2 = "";

 

        switch (curScene) {

        case 0:

          curScene = 1;

          message = "Your journey begins at a fork in the road.";

          decision1 = "Take the Path";

          decision2 = "Take the Bridge";

 

          // Show the second decision

          document.getElementById("decision2").style.visibility = "visible";

          break;

        case 1:

          if (decision == 1) {

            curScene = 2

            message = "You have arrived at a cute little house in the woods.";

            decision1 = "Walk around Back";

            decision2 = "Knock on Door";

          }

          else {

            curScene = 3;

            message = "You are standing on the bridge overlooking a peaceful stream.";

            decision1 = "Walk across Bridge";

            decision2 = "Gaze into Stream";

          }

          break;

        case 2:

          if (decision == 1) {

            curScene = 4

            message = "Peeking through the window, you see a witch inside the house.";

            decision1 = "Sneak by Window";

            decision2 = "Wave at Witch";

          }

          else {

            curScene = 5;

            message = "Sorry, a witch lives in the house and you just became part of her stew.";

            decision1 = "Start Over";

            decision2 = "";

 

            // Hide the second decision

            document.getElementById("decision2").style.visibility = "hidden";

          }

          break;

        case 3:

          if (decision == 1) {

            curScene = 6

            message = "Sorry, a troll lives on the other side of the bridge and you just became his lunch.";

            decision1 = "Start Over";

            decision2 = "";

 

            // Hide the second decision

            document.getElementById("decision2").style.visibility = "hidden";

          }

          else {

            curScene = 7;

            message = "Your stare is interrupted by the arrival of a huge troll.";

            decision1 = "Say Hello to Troll";

            decision2 = "Jump into Stream";

          }

          break;

        case 4:

          if (decision == 1) {

            curScene = 8

            decision1 = "?";

            decision2 = "?";

          }

          else {

            curScene = 5;

            message = "Sorry, you became part of the witch's stew.";

            decision1 = "Start Over";

            decision2 = "";

 

            // Hide the second decision

            document.getElementById("decision2").style.visibility = "hidden";

          }

          break;

        case 5:

          curScene = 0;

          decision1 = "Start Game";

          decision2 = "";

          break;

        case 6:

          curScene = 0;

          decision1 = "Start Game";

          decision2 = "";

          break;

        case 7:

          if (decision == 1) {

            curScene = 6

            message = "Sorry, you became the troll's tasty lunch.";

            decision1 = "Start Over";

            decision2 = "";

 

            // Hide the second decision

            document.getElementById("decision2").style.visibility = "hidden";

          }

          else {

            curScene = 9;

            decision1 = "?";

            decision2 = "?";

          }

          break;

        case 8:

          // TO BE CONTINUED

          break;

        case 9:

          // TO BE CONTINUED

          break;

        }

 

        // Update the scene image

        document.getElementById("sceneimg").src = "scene" + curScene + ".png";

 

        // Update the scene description text and decisions

        replaceNodeText("scenetext", message);

        replaceNodeText("decision1", decision1);

        replaceNodeText("decision2", decision2);

 

        // Update the decision history

        var history = document.getElementById("history");

        if (curScene != 0) {

          // Add the latest decision to the history

          var decisionElem = document.createElement("p");

          decisionElem.appendChild(document.createTextNode("Decision " + decision + " -> Scene " + curScene + " : " + message));

          history.appendChild(decisionElem);

        }

        else {

          // Clear the decision history

          while (history.firstChild)

            history.removeChild(history.firstChild);

        }

      }

    </script>

  </head>

 

  <body>

    <div style="margin-top:100px; text-align:center">

      <img id="sceneimg" src="scene0.png" alt="Stick Figure Adventure" /><br />

      <div id="scenetext"></div><br />

      <span id="decision1" class="decision" onclick="changeScene(1)"

        onmouseover="this.className = 'decisionhover'"

        onmouseout="this.className = 'decision'">Start Game</span>

      <span id="decision2" class="decision" onclick="changeScene(2)"

        onmouseover="this.className = 'decisionhover'"

        onmouseout="this.className = 'decision'"

        style="visibility:hidden"></span>

      <div id="history" style="background-color:#EEEEEE"></div>

    </div>

  </body>

</html>

       部分结果:

          

       上面的按钮是用span标签来做的,而不是input button,为了更像一个按钮,即鼠标在上面的时候指针是手势而不是文本选择。我们可以使用CSS中的cursor,修改后如下:

<span id="decision1" class="decision" onclick="changeScene(1)"

   onmouseover="this.className = 'decisionhover'"

   onmouseout="this.className = 'decision'" style="cursor:pointer;">

Start Game

</span>

       当然也可以把cursor加在class中,如果同时存在则会屏蔽class的。

如果想为标签添加文本值(例如<p>,<input>、<span>等),首先要求该标签支持创建文本节点的,然后可以使用innerHTML直接添加,而且添加的内容可以是HTML标签等,如下:

<html>

  <head>

    <title>innerHTMLtest.html</title>

    <script type="text/javascript">

       window.onload=function(){

           var pObj = document.getElementById("paragraph");

           pObj.innerHTML="This is <i><strong>my</strong></i> paragraph !";

       }

    </script>

  </head>

  <body>

    <p id="paragraph"></p>

  </body>

</html>

       结果如下:This is my paragraph!

利用innerHTML也可以将内容追加在原文本后:elem.innerHTML +=“some texts”;

如果要取得标签下的文本值,有两种方法:

1、  使用innerHTML直接获取

2、  使用nodeValue获取

范例:对比两种获取文本内容的方法。

<html>

  <head>

    <title>innerHTMLtest.html</title>

    <script type="text/javascript">

       window.onload=function(){

           var pObj = document.getElementById("paragraph");

           alert("DOM:" + getText(pObj));

           alert("innerHTML:" + pObj.innerHTML);

       }

 

       function getText(parNode){

           var context="";

           for(var i=0; i<parNode.childNodes.length; i++){

              var temp = parNode.childNodes[i].nodeValue;

              if(temp != null){

                  context += temp;

              }else{//temp等于null表示其不是文本类型

                  context += getText(parNode.childNodes[i]);

              }

           }

           return context;

       }

    </script>

  </head>

  <body>

    <p id="paragraph">This is a <i><strong>example</strong></i> !</p>

    <span id="" ></span>

  </body>

</html>

       结果如下:

   

       使用DOM标准的,需要调用递归函数来遍历所有文本内容,因为节点下难免会有子节点。有关节点的部分属性如下:

nodeValue:存储节点的值,只限于文本与属性节点使用(不含元素);

nodeType:节点类型,例如它是document或text等,但以代号表示;

childNodes:包含节点下所有节点的数组,以出现在HTML代码中的顺序而排列;

firstChild:节点下的第一个子节点。

nodeValue除了获取文本值,也可以取得标签里的属性的值,例如HTML中存在一个标签:

<input type="button" value="确定" id="confirm" />

获取“确定”这个值,方法如下:

document.getElementById("confirm").getAttributeNode("value").nodeValue

使用innerHTML十分便捷,只不过,innerHTML不是DOM标准内容,如果要使用DOM标准,则需要以下3个步骤实现:

1)       移除所有子节点;

2)       根据新内容创建新的文本节点;

3)       把新创建的文本子节点附加在节点下;

范例:利用DOM标准改变节点文本值。

<html>

    <head>

        <title>innerDemo.html</title>

        <script type="text/javascript">

            window.onload = function(){

                var pNode = document.getElementById("paragraph");

                while (pNode.firstChild) { //1、移除所有子节点

                    pNode.removeChild(pNode.firstChild);

                }

                //2、创建新的文本字节

                var textNode = document.createTextNode("New content.");

                //3、添加到父节点上

                pNode.appendChild(textNode);

            }

        </script>

    </head>

    <body>

        <p id="paragraph">

            Hello World!

        </p>

    </body>

</html>

       上面的步骤比较繁琐一点,所以一般可以使用innerHTML的地方就使用innerHTML。

 

下面再介绍一个方法:document.getElementsByTagName,这方法以数组的形式返回指定tag标签下的所有对象。例如,可以用于image对象,然后隐藏所有image对象或者改变他们。

范例:游戏王洗牌。一键将所有牌翻转。

<html>

    <head>

        <title>MyGame.html</title>

       <script type="text/javascript">

           function inverseCards(){

              var gameImgs = document.getElementById("imgs");

              var cards = gameImgs.getElementsByTagName("img");

              for(var i=0; i<cards.length; i++){

                  cards[i].src="reverse.bmp";

              }

           }

       </script>

    </head>

    <body>

        <div style="margin:50px;text-align:center" id="imgs">

            <img id="magician" src="magician.bmp">

           <img id="heart" src="heart.bmp">

           <img id="summonedSkull" src="summonedSkull.bmp">

        </div>

       <divalign="center">

           <input type="button" value="INVERSE"

           style="padding:4px;font-size:110%" onclick="inverseCards()">

       </div>

    </body>

</html>

       打开页面:

       点击inverse按钮,结果如下:

       如果不想指定某个div下的image对象,也可以这样写,以获取页面内所有的image对象,因为document是整个DOM的根:

       document.getElementsByTagName("img");

       上面在div标签中使用到的align属性在新标准中已经不建议使用了。推荐使用的是CSS样式:text-align。

HTML DOM中有一个对象:Style,可以用于设置单一样式属性,其中属性visibility与display都可以用于设置节点是否被显示。但他们之间有一定区别。

See also:http://www.vanseodesign.com/css/visibility-vs-display/

http://www.vanseodesign.com/blog/demo/display-visibility.html

              http://homepage.yesky.com/55/2336055.shtml

 

改变某个便签的样式,可以直接这样来:

οnmοuseοver="this.className = 'newClassName'"

或者触发某个函数,函数中这样写:

document.getElementById(ID).className = "newClassName"

明显是第一种比较方便一点。

 

随机函数:

产生1~6的数:

Floor( (Math.random() * 6) + 1 )

http://www.random.org/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值