aboutsummaryrefslogtreecommitdiff
path: root/files/zh-cn/learn/javascript/first_steps/silly_story_generator/index.html
blob: f99ff16949dd570546640b500067fd7031ee62e8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
---
title: 笑话生成器
slug: Learn/JavaScript/First_steps/Silly_story_generator
tags:
  - JavaScript
  - 初学者
  - 变量
  - 字符串
  - 学习
  - 操作符
  - 数字
  - 数组
  - 测试
  - 脚本代码
  - 课程设计
translation_of: Learn/JavaScript/First_steps/Silly_story_generator
---
<div>{{LearnSidebar}}</div>

<div>{{PreviousMenu("Learn/JavaScript/First_steps/Arrays", "Learn/JavaScript/First_steps")}}</div>

<p class="summary">本节是一个小测验,要求你运用所学知识制作一个笑话生成器。祝玩的愉快!</p>

<table class="learn-box standard-table">
 <tbody>
  <tr>
   <th scope="row">预备知识:</th>
   <td>请读完本章所有小节的内容后再开始这个测验。</td>
  </tr>
  <tr>
   <th scope="row">目标:</th>
   <td>测试你对变量、数字、操作符、字符串和数组等 Javascript 基本概念的理解程度。</td>
  </tr>
 </tbody>
</table>

<h2 id="起点">起点</h2>

<p>测验开始之前需要下载并保存 <a class="external external-icon" href="https://github.com/roy-tian/learning-area/blob/master/javascript/introduction-to-js-1/assessment-start/index.html">index.html</a><a class="external external-icon" href="https://github.com/roy-tian/learning-area/blob/master/javascript/introduction-to-js-1/assessment-start/style.css">style.css</a><a class="external external-icon" href="https://github.com/roy-tian/learning-area/blob/master/javascript/introduction-to-js-1/assessment-start/raw-text.txt">raw-text.txt</a></p>

<div class="note">
<p><strong>注:</strong> 你还可以用类似 <a class="external external-icon" href="http://jsbin.com/">JSBin</a> 或 <a class="external external-icon" href="https://thimble.mozilla.org/">Thimble</a> 这些在线编辑器来完成测验。你可以把 HTML、CSS 及 JavaScript 代码复制过去。如果你选的工具没有独立的 JavaScript 版面,可以随时在 HTML 页面中添加 <code>&lt;script&gt;</code> 元素。</p>
</div>

<h2 id="项目简介">项目简介</h2>

<p>我们提供了一些原始的 HTML / CSS,以及若干字符串和 JavaScript 函数,还需要你来编写一些 JavaScript 代码让项目运行起来:</p>

<ul>
 <li>点击“随机生成笑话”按钮时生成一则笑话。</li>
 <li>若“生成”按钮按下之前,你在“输入自定义的名字”文字框中输入了一个自定义名字,那么生成的笑话中原有的名字(李雷 / Bob)将被取代。</li>
 <li>通过选择国家名称的单选按钮来确定界面语言以及笑话中温度和重量的制式。</li>
 <li>点一次按钮,生成一个新故事。点一次生成一个……</li>
</ul>

<p>可以尝试操作一下:(别偷看源代码哦!)</p>

<div class="hidden">
<h6 id="Silly_story_generator">Silly story generator</h6>

<pre class="brush: html notranslate">&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
    &lt;meta charset="utf-8"&gt;
    &lt;style&gt;
        body {
            font-family: helvetica, sans-serif;
            width: 350px;
            border: 1px solid;
            padding: 1em;
        }
        label {
            font-weight: bold;
        }
        div {
            padding-bottom: 20px;
        }
        input[type="text"] {
            padding: 5px;
            width: 150px;
        }
        p {
            background: #FFC125;
            color: #5E2612;
            padding: 10px;
            visibility: hidden;
        }
    &lt;/style&gt;
&lt;/head&gt;

&lt;body&gt;
&lt;div&gt;
    &lt;label for="customname" id="lbl-customname"&gt;请输入自定义的名字:&lt;/label&gt;
    &lt;input id="customname" type="text" placeholder="李雷"&gt;
&lt;/div&gt;
&lt;div&gt;
      &lt;label for="metric"&gt;公制&lt;/label&gt;&lt;input id="metric" type="radio" name="measure" value="metric" checked&gt;
      &lt;label for="american"&gt;美制&lt;/label&gt;&lt;input id="american" type="radio" name="measure" value="american"&gt;
&lt;/div&gt;
&lt;div&gt;
    &lt;button class="randomize"&gt;随机生成笑话&lt;/button&gt;
&lt;/div&gt;
&lt;!-- Thanks a lot to Willy Aguirre for his help with the code for this assessment --&gt;
&lt;p class="story"&gt;&lt;/p&gt;

&lt;script&gt;
const customName = document.getElementById('customname');
const randomize = document.querySelector('.randomize');
const story = document.querySelector('.story');

function randomValueFromArray(array){
  const random = Math.floor(Math.random() * array.length);
  return array[random];
}

let storyText = '今天气温 35 摄氏度,:insertx:出门散步。当走到:inserty:门前时,突然就:insertz:。人们都惊呆了,李雷全程目睹但并没有慌,因为:insertx:是一个 140 公斤的胖子,天气又辣么热。';
let insertX = ['怪兽威利', '大老爹', '圣诞老人'];
let insertY = ['肯德基', '迪士尼乐园', '白宫'];
let insertZ = ['自燃了', '在人行道化成了一坨泥', '变成一只鼻涕虫爬走了'];

randomize.addEventListener('click', result);

function result() {
  let newStory = storyText;

  let xItem = randomValueFromArray(insertX);
  let yItem = randomValueFromArray(insertY);
  let zItem = randomValueFromArray(insertZ);

  newStory = newStory.replace(':insertx:', xItem);
  newStory = newStory.replace(':insertx:', xItem);
  newStory = newStory.replace(':inserty:', yItem);
  newStory = newStory.replace(':insertz:', zItem);

  if(customName.value !== '') {
    const name = customName.value;
    newStory = newStory.replace('李雷', name);
  }

  if(document.getElementById("american").checked) {
    const weight = Math.round(140 * 2.20462) + ' 磅';
    const temperature =  Math.round(35 * 9 / 5 + 32) + ' 华氏度';
    newStory = newStory.replace('35 摄氏度', temperature);
    newStory = newStory.replace('140 公斤', weight);
  }

  story.textContent = newStory;
  story.style.visibility = 'visible';
}
&lt;/script&gt;

&lt;/body&gt;
&lt;/html&gt;</pre>
</div>

<p>{{ EmbedLiveSample('Silly_story_generator', '100%', 350, "", "", "hide-codepen-jsfiddle") }}</p>

<div class="note">
<p><strong>译注: </strong><a class="external external-icon">点击在线试用</a> 汉化版本。有兴趣还可以在本节结束后回来 <a class="external external-icon" href="https://github.com/roy-tian/learning-area/tree/master/javascript/introduction-to-js-1/assessment-finished">看看代码</a>。(没兴趣就跳过吧 :)</p>
</div>

<h2 id="步骤">步骤</h2>

<p>以下是你的工作。</p>

<p>初始化变量和函数:</p>

<ol>
 <li>将刚下载的文本文件中的“1. 定义变量和函数”标题项下所有代码复制粘贴至 main.js 中。此时你就有了三个变量(<code>customName</code> 是对“输入自定义的名字”文本框的引用,<code>randomize</code> 是对“随机生成笑话”按钮的引用,<code>story</code> 是对 HTML 底部的、准备存放笑话的 {{htmlelement("p")}} 元素的引用)和一个函数(<code>randomValueFromArray()</code> 取一个数组作参数,随机返回数组中的一个元素)。</li>
 <li>然后是文本文件的第二节——“2. 纯文本字符串”。这里包含了一些字符串,这些字符串是项目的输入信息。你应该在 main.js 文件中用变量来保存它们。
  <ol>
   <li><code>storyText</code> 变量保存第一个长字符串,“今天气温……”。</li>
   <li><code>insertX</code> 数组保存第一组三个字符串,“怪兽威利……”。</li>
   <li><code>insertY</code> 数组保存第二组三个字符串。“肯德基……”。</li>
   <li><code>insertZ</code> 数组保存第三组三个字符串。“自燃了……”。</li>
  </ol>
 </li>
</ol>

<p>放置事件处理器并补全:</p>

<ol>
 <li>返回刚才的文本文件。</li>
 <li>将“3. 事件监听器和未完成的函数定义”标题项下的代码复制粘贴至 <code>main.js</code> 文件。这将:
  <ul>
   <li><code>randomize</code> 变量增加一个点击事件的监听器。于是当所引用的按钮被点击时,<code>result()</code> 函数就会运行。</li>
   <li>为代码添加一个未完成的 <code>result()</code> 函数定义。本测验剩下的工作就是完成这个函数,让程序正常运行起来。</li>
  </ul>
 </li>
</ol>

<p>补全 <code>result()</code> 函数:</p>

<ol>
 <li><code>newStory</code> 的值设置为 <code>storyText</code>。声明新变量有必要的,只有这样才能在每次按下按钮后、在函数运行时生成一个新的随机笑话。如果直接操作 <code>storyText</code> 则只能生成一次新故事</li>
 <li><code>xItem</code><code>yItem</code> 和 <code>zItem</code> 分别设置为 <code>randomValueFromArray(insertX)</code><code>randomValueFromArray(insertY)</code><code>randomValueFromArray(insertZ)</code></li>
 <li>接下来将 <code>newStory</code> 中的占位符(<code>:inserta:</code><code>:insertb:</code><code>:insertc:</code> )替换为 <code>xItem</code><code>yItem</code> 和 <code>zItem</code>。有专用的字符串方法可供使用,并用该方法的返回值为 <code>newStory</code> 赋值。每当按下按钮时,这些占位符都会替换为随机的笑话字符串。再给你一点提示,我们所说的这种方法每次只会将所找到的首个子字符串进行替换,因此该方法对某个占位符需要执行两次。</li>
 <li>在第一个 <code>if</code> 块中再次调用这个字符串替换方法,以使 <code>newStory</code> 字符串中的名字“李雷”替换为变量 <code>name</code> 的值 。这里我们说:“如果 <code>customName</code> 中有值,就把故事里的 “李雷”替换成它。” 如果是汉化版将newStory中的“李雷”替换成 <code>name</code> 的值;</li>
 <li>在第二个 <code>if</code> 块中检查 <code>american</code> 单选按钮是否被选中。如果选中,就要将故事中的重量和温度值从公斤和摄氏度转换为磅和华氏度,具体事项如下:
  <ol>
   <li>确定英美单位的转换公式。</li>
   <li>定义变量 <code>weight</code><code>temperature</code> 的行中,分别将美制单位按公式转化为英制,用 <code>Math.round()</code> 对计算结果取整。然后将英式单位连接到末尾。</li>
   <li>就在上述两个变量的定义下方增加两个字符串置换操作,将“35 摄氏度”替换为 <code>temperature</code> 的值,将“140 公斤”替换为 <code>weight</code> 的值。</li>
  </ol>
 </li>
 <li>最后,在函数倒数第二行,将 <code>story.textContent</code>(程序中显示笑话结果的段落) 赋值为 <code>newStory</code></li>
</ol>

<h2 id="提示">提示</h2>

<ul>
 <li>除了在 HTML 文件中引入这个 JavaScript 文件之外,完全不需要编辑 HTML。</li>
 <li>如果你不确定当前 JavaScript 是否正确添加到了你的 HTML 中,可以尝试暂时删除 JavaScript 文件的所有内容,然后加上一些简单但效果显著的 JavaScript 代码,保存文件并刷新浏览器。下面的示例会让 {{htmlelement("html")}} 背景变为红色,如果 JavaScript 成功加载,那么整个浏览器窗口将变红:</li>
 <li>
  <pre class="brush: js line-numbers  language-js notranslate"><code class="language-js">document<span class="punctuation token">.</span><span class="function token">querySelector</span><span class="punctuation token">(</span><span class="string token">'html'</span><span class="punctuation token">)</span><span class="punctuation token">.</span>style<span class="punctuation token">.</span>backgroundColor <span class="operator token">=</span> <span class="string token">'red'</span><span class="punctuation token">;</span></code></pre>
 </li>
 <li><code class="language-js"><span class="punctuation token"><a href="/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Math/round">Math.round()</a></span></code> 是 Javascript 的内建函数,可取得与传入小数最接近的整数。</li>
 <li>本示例中有三类字符串需要替换。可以多次重复 <code>replace()</code> 方法,也可使用正则表达式。例如:<code>var text = 'I am the biggest lover, I love my love';</code> 或 <code>text.replace(/love/g,'like');</code> 会将所有的“love”替换为“like”。记住,字符串本身是不可修改的!</li>
</ul>

<h2 id="测验">测验</h2>

<p>如果你是在课堂上进行这个测验,你可以把作品交给导师或教授去打分了。如果你是在自学,也可以在 <a href="https://discourse.mozilla.org/t/silly-story-generator-assessment/24686">本节测验的讨论页</a> 或者 <a href="https://wiki.mozilla.org/IRC">Mozilla 聊天室 </a><a href="irc://irc.mozilla.org/mdn">#mdn</a> 频道取得帮助。要自己先尝试,作弊是不会有收获的!</p>

<p>{{PreviousMenu("Learn/JavaScript/First_steps/Arrays", "Learn/JavaScript/First_steps")}}</p>

<h2 id="本章目录">本章目录</h2>

<ul>
 <li><a href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/What_is_JavaScript">JavaScript 是什么?</a></li>
 <li><a href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/A_first_splash">JavaScript 初体验</a></li>
 <li><a href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/What_went_wrong">查找并解决 JavaScript 代码的错误 </a></li>
 <li><a href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Variables">变量:储存所需信息</a></li>
 <li><a href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Math">数字和运算符:JavaScript 的基本算数</a></li>
 <li><a href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Strings">字符串:JavaScript 文本的处理</a></li>
 <li><a href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Useful_string_methods">字符串的一些实用方法</a></li>
 <li><a href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Arrays">数组</a></li>
 <li><a href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Silly_story_generator">课程评估:笑话机</a></li>
</ul>