了解 JavaScript (4)– 第一个 Web 应用程序


在下面的例子中,我们将要构建一个 Bingo 卡片游戏,每个示例演示 JavaScript 的不同方面,通过每次的改进将会得到最终有效的 Bingo 卡片。

Bingo 卡片的内容

美国 Bingo 卡片是 5 X 5 的方形,5 个列上标明 B-I-N-G-O,格子中包含 1~75 的数字。正中间是一个空格子,常常印着 free。每列可以包含的范围如下:

  • B 列包含数字 1~15
  • I 列包含数字 16~30
  • N 列包含数字 31~45
  • G 列包含数字 46~60
  • O 列包含数字 61~75

原始1、第一个简单的 JavaScript 循环

bingo.html,这个页面建立 Bingo 卡片的框架。

doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Make Your Own Bingotitle>
  <link rel="stylesheet" href="bingo.css">
  <script src="bingo.js">script>
head>
<body>
<h1>Create A Bingo Cardh1>
<table>
<tr>
  <th>Bth>
  <th>Ith>
  <th>Nth>
  <th>Gth>
  <th>Oth>  
tr>

<tr>
  <td id="square0"> td>
  <td id="square5"> td>
  <td id="square10"> td>
  <td id="square14"> td>
  <td id="square19"> td>  
tr>

<tr>
  <td id="square1"> td>
  <td id="square6"> td>
  <td id="square11"> td>
  <td id="square15"> td>
  <td id="square20"> td>  
tr>

<tr>
  <td id="square2"> td>
  <td id="square7"> td>
  <td id="free">Freetd>
  <td id="square16"> td>
  <td id="square21"> td>  
tr>

<tr>
  <td id="square3"> td>
  <td id="square8"> td>
  <td id="square12"> td>
  <td id="square17"> td>
  <td id="square22"> td>  
tr>

<tr>
  <td id="square4"> td>
  <td id="square9"> td>
  <td id="square13"> td>
  <td id="square18"> td>
  <td id="square23"> td>  
tr>
table>
<p><a href="../111.html" id="reload">Click herea> to create a new cardp>
body>
html>

bingo.css 为 Bingo 卡片添加样式

@charset "utf-8";
/* CSS Document */
body{
    background-color: white;
    color: black;
    font-size: 20px;
    font-family: "Lucida Console", Verdana, Arial, Helvetica, sans-serif;
}

h1, th{
    font-family: Georgia, "Times New Roman", Times, serif;
}

h1 {
    font-size: 28px;
}

table{
    border-collapse: collapse;
}
th, td{
    padding: 10px;
    border: 2px #666 solid;
    text-align: center;
    width: 20%;
}

#free, .pickedBG{
    background-color: #f66;
}
.winningBG{
    background-image: url(redFlash.gif);
}

我们先看看上面的 HTML 和 CSS 页面,这个是 Bingo 卡片的框架,包含 6 行 5 列的表格,表格的第一行是BINGO字母,且第三行中间是一个 Free 表格,每个单元格都有一个 id 属性,脚本将使用此 id 操纵这些单元格内容。id 采用 square0、square1、square2,直到 square23 分布如下图,在页面的底部,有一个用来生成新卡片的链接。

我们将要用循环语句,最常用的就是 for 循环,这种循环使用一个计数器(counter),计数器是一个变量,它的初值是某个值。在测试条件得不到满足的时候就会结束。

我们将 bingo.html 标签中的