JS 技能测试:笑话生成器

题目链接

题目要求:

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

HTML 代码:

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
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width">

<title>笑话机</title>

<link href="style.css" rel="stylesheet">
<script src="main.js" defer></script>
</head>

<body>
<div>
<label for="customname">输入自定义名字:</label>
<input id="customname" type="text" placeholder="李雷">
</div>
<div>
<label for="metric">公制</label><input id="metric" type="radio" name="measure" value="metric" checked>
<label for="american">美制</label><input id="american" type="radio" name="measure" value="american">
</div>
<div>
<button class="randomize">生成随机笑话</button>
</div>
<!-- 鸣谢:Willy Aguirre 提供的测试代码 -->
<p class="story"></p>
</body>
</html>

CSS 代码:

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
body {
font-family: sans-serif;
width: 350px;
}

label {
font-weight: bold;
}

div {
padding-bottom: 20px;
}

input[type="text"] {
padding: 5px;
width: 150px;
}

p {
background: #FFC125;
color: #5E2612;
padding: 10px;
visibility: hidden;
}

JS 代码:

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
const customName = document.getElementById('customname');
const randomize = document.querySelector('.randomize');
const story = document.querySelector('.story');

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

let storyText = '今天气温 34 摄氏度,:inserta:出去遛弯。当走到:insertb:门前时,突然就:insertc:。人们都惊呆了,李雷全程目睹但并没有慌,因为:inserta:是一个 130 公斤的胖子,天气又辣么热。';
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(':inserta:',xItem);
newStory = newStory.replace(':insertb:',yItem);
newStory = newStory.replace(':insertc:',zItem);
newStory = newStory.replace(':inserta:',xItem);
if(customName.value !== '') {
let name = customName.value;
newStory = newStory.replace('李雷',name);
}

if(document.getElementById("american").checked) {
let weight = Math.round(300);
let temperature = Math.round(94);
newStory = newStory.replace('34 摄氏度',`${temperature} 华氏度`);
newStory = newStory.replace('130 公斤',`${weight} 磅`);
}

story.textContent = newStory;
story.style.visibility = 'visible';
}