前言

由于上一篇流水账太长了,移动端的浏览器出现了不知名故障,只能拆开一部分分到这里来了。这一部分主要记录写过的习题,方便可以随时随地回顾一下。不过将文章拆开来也不是一件坏事,以前复习来翻文章要要翻老久了。

习题

例一

1
2
3
4
5
6
7
8
9
<label for="weather">选择今天的天气</label>
<select name="" id="weather">
<option value="">--请做出选择--</option>
<option value="sunny">"晴天"</option>
<option value="rainy">"雨天"</option>
<option value="snowing">"雪天"</option>
<option value="overcast">"阴天"</option>
</select>
<p></p>
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
const select = document.querySelector("select");
const para = document.querySelector("p");

select.addEventListener("change", setweater);

function setweater() {
const choice = select.value;


if (choice === "sunny") {
para.textContent = "阳光明媚。穿上短裤吧!去海滩,或公园,吃个冰淇淋。";
}
else if (choice === "rainy") {
para.textContent = "外面下着雨;带上雨衣和雨伞,不要在外面呆太久。";
}
else if (choice === "snowing") {
para.textContent = "大雪纷飞,天寒地冻!最好呆在家里喝杯热巧克力,或者去堆个雪人。";
}
else if (choice === "overcast") {
para.textContent = "虽然没有下雨,但天空灰蒙蒙的,随时都可能变天,所以要带一件雨衣以防万一。";
}
else {
para.textContent = "";
}
}

选择天气输出对应字符串。

例二

1
2
3
<label for="search">Search by contact name:</label>
<input id="search" type="text" />
<button>Search</button>
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
const contacts = [
"Chris:2232322",
"Sarah:3453456",
"Bill:7654322",
"Mary:9998769",
"Dianne:9384975",
];
const para = document.querySelector("p");
const input = document.querySelector("input");
const btn = document.querySelector("button");

btn.addEventListener("click", function () {
let searchName = input.value.toLowerCase();
input.value = "";//清空搜索框
input.focus();//重新聚焦搜索框
for (let i = 0; i <= contacts.length; i++) {
//split() 方法接受一个模式,通过搜索模式将字符串分割成一个有序的子串列表,将这些子串放入一个数组,并返回该数组。
let splitContact = contacts[i].split(":");
if (splitContact[0].toLowerCase() === searchName) {
para.textContent = splitContact[0] + "'s number name is" + splitContact[1] + ".";
break;
} else if (i === contacts.length - 1) {
para.textContent = "Can not found.";
}
}
});

查找用户并输出用户id

例三

1
2
<button>点击我生成随机名字</button>
<p></p>
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
const names = [
"Chris",
"Li Kang",
"Anne",
"Francesca",
"Mustafa",
"Tina",
"Bert",
"Jada",
];

const para = document.querySelector("p");
const btn = document.querySelector("button");

btn.addEventListener("click", () => {
getRandomName(names);
});

function getRandomNum (min, max) {
const randomNum = Math.floor(Math.random() * (max - min) + min);
return randomNum;
};

function getRandomName(array) {
const choice = array[getRandomNum(0, names.length)];
para.textContent = choice;
};

点击按钮随机生成数组内的名字

例四

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
.msgBox {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 242px;
background: #eee;
}

.msgBox p {
padding-left: 82px;
background-position: 25px center;
background-repeat: no-repeat;
line-height: 1.5;
padding: 10px 20px;
color: #333;
}

.msgBox button {
background: none;
border: none;
position: absolute;
top: 0;
right: 0;
font-size: 1.1rem;
color: #aaa;
}
1
2
<button id="btn1">Display message box:waring</button>
<button id="btn2">Display message box:Chat</button>
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
const btn1 = document.querySelector("#btn1");
const btn2 = document.querySelector("#btn2");

btn1.onclick = () => {
displayMessage("Your inbox is almost full — delete some mails","warning");
};

btn2.onclick = () => {
displayMessage("Brian: Hi there, how are you today?","Chat");
};
//btn.onclick = displayMessage(`Woo, this is a different message!`);
//不可以这样写,函数会直接调用。
function displayMessage(msgText, msgType) {
const html = document.querySelector("html");
const pannel = document.createElement("div");
const msg = document.createElement("p");
const closeButton = document.createElement("button");

if (msgType === "warning") {
msg.style.backgroundImage = "url(icons/warning.png)";
pannel.style.backgroundColor = "red";
}else if (msgType === "Chat") {
msg.style.backgroundImage = "url(icons/warning.png)";
pannel.style.backgroundColor = "aqua";
}else {
msg.style.paddingLeft = "20px";
}


pannel.setAttribute("class", "msgBox");
html.appendChild(pannel);


msg.textContent = msgText;
pannel.appendChild(msg);


closeButton.textContent = `x`;
pannel.appendChild(closeButton);

closeButton.onclick = function() {
pannel.parentNode.removeChild(pannel);
};
};

点击不同按钮会显示对应Warning区块或者Chat区块,可点击区块右上角”x”关闭

例五(类的创建与继承)

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
class Shape {
constructor(name, sides, sideLength) {
this.name = name;
this.sides = sides;
this.sideLength = sideLength;
}

calcPerimeter() {
console.log(`Total length is ${this.sides * this.sideLength}`);
}

}

class sameLenth extends Shape {
constructor(sideLength) {
super(name);
this.sides = 4;
this.sideLength = sideLength;
}

calcArea() {
console.log(`Square is ${this.sideLength * this.sideLength}`);
}
}

const shape1 = new Shape("Square", 4, 5);

shape1.calcPerimeter();

const triangle = new Shape("triangle", 3, 3);

triangle.calcPerimeter();

const square = new sameLenth(5);

square.calcPerimeter();
square.calcArea();

控制台输出结果:Total length is 20;Total length is 9;Total length is 20;Square is 25

例六(使用JSON)

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
html {
font-family: 'helvetica neue', helvetica, arial, sans-serif;
}

body {
width: 800px;
margin: 0 auto;
}

h1,
h2 {
font-family: 'Faster One', cursive;
}

/* header styles */

h1 {
font-size: 4rem;
text-align: center;
}

header p {
font-size: 1.3rem;
font-weight: bold;
text-align: center;
}

/* section styles */

section article {
width: 33%;
float: left;
}

section p {
margin: 5px 0;
}

section ul {
margin-top: 0;
}

h2 {
font-size: 2.5rem;
letter-spacing: -5px;
margin-bottom: 10px;
}
1
2
<header></header>
<section></section>
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
async function populate() {
const requestURL =
"https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json";
const request = new Request(requestURL);

const response = await fetch(request);
const superHeroes = await response.json();

populateHeader(superHeroes);
populateHeroes(superHeroes);
}

function populateHeader(obj) {
const header = document.querySelector("header");
const myH1 = document.createElement("h1");
myH1.textContent = obj.squadName;
header.appendChild(myH1);

const mypara = document.createElement("p");
mypara.textContent = `Hometown: ${obj.homeTown} // Fromed: ${obj.formed}`;
header.appendChild(mypara);
}

function populateHeroes(obj) {
const section = document.querySelector("section");
const heroes = obj.members;

for (const hero of heroes) {
const myArticle = document.createElement("article");
const myH2 = document.createElement("h2");
const mypara1 = document.createElement("p");
const mypara2 = document.createElement("p");
const mypara3 = document.createElement("p");
const mylist = document.createElement("ul");

myH2.textContent = hero.name;
mypara1.textContent = `Secret identity: ${hero.secretIdentity}`;
mypara2.textContent = `Age: ${hero.age}`;
mypara3.textContent = "Superpowers:";

const superPowers = hero.powers;
for (const power of superPowers) {
const listItem = document.createElement("li");
listItem.textContent = power;
mylist.appendChild(listItem);
}



myArticle.appendChild(myH2);
myArticle.appendChild(mypara1);
myArticle.appendChild(mypara2);
myArticle.appendChild(mypara3);
myArticle.appendChild(mylist);

section.appendChild(myArticle);
}
}

populate();

这里附上JSON内容,代码中不必加入。

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
{
"squadName" : "Super Hero Squad",
"homeTown" : "Metro City",
"formed" : 2016,
"secretBase" : "Super tower",
"active" : true,
"members" : [
{
"name" : "Molecule Man",
"age" : 29,
"secretIdentity" : "Dan Jukes",
"powers" : [
"Radiation resistance",
"Turning tiny",
"Radiation blast"
]
},
{
"name" : "Madame Uppercut",
"age" : 39,
"secretIdentity" : "Jane Wilson",
"powers" : [
"Million tonne punch",
"Damage resistance",
"Superhuman reflexes"
]
},
{
"name" : "Eternal Flame",
"age" : 1000000,
"secretIdentity" : "Unknown",
"powers" : [
"Immortality",
"Heat Immunity",
"Inferno",
"Teleportation",
"Interdimensional travel"
]
}
]
}

会输出一个superhero的海报

在此函数中,前四行使用Fetch API从服务器获取JSON数据:
- 声明了requestURL变量以存储GitHub的URL
- 使用该URL初始化一个新的Request对象(这一步可以省略)
- 使用fetch()函数进行网络请求它返回一个 Response对象
- 使用Response对象的json()函数将响应作为JSON获取

注:fetch() API是异步的,要在使用fetch API的函数名称之前添加async关键字,并在任何异步函数的调用之前添加await关键字。

例七(异步JS使用promise)

JSON文件内容

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
[
{
"name" : "baked beans",
"price" : 0.40,
"image" : "beans.jpg",
"type" : "vegetables"
},
// ...中间还有很多行,没有用就省略掉了。
{
"name" : "carrot and coriander soup",
"price" : 1.49,
"image" : "carrotcoriander.jpg",
"type" : "soup"
}
]

阶段1

这个例子使用fetch()发送一个替代XMLHttpRequest的http请求。

1
2
3
4
5
6
const promise = fetch("https://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/products.json");
console.log(promise);
promise.then((Response) => {
console.log(`已收到响应:${Response.status}`);
});
console.log(`已发送请求`);

控制台输出:

  • Promise { : “pending” }
  • 已发送请求……
  • 已收到响应:200

阶段2

这个例子演示了链式使用Promise。

1
2
3
4
5
6
7
const fetchPromis = fetch("https://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/products.json");
fetchPromis.then(Response => {
const jsonpromise = Response.json();
jsonpromise.then(json => {
console.log(json[0].name);
});
});

控制台输出:baked beans

阶段3

这个例子优化了阶段2的代码

1
2
3
4
5
6
const fetchPromis = fetch("https://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/products.json");
fetchPromis
.then(Response => Response.json())
.then(data => {
console.log(data[0].name);
});

控制台输出:baked beans

阶段4

这个例子使用.catch()捕获未能fetch()成功的错误

1
2
3
4
5
6
7
8
9
10
11
const fetchPromis = fetch("https://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/products.json");//这个是可用链接
const fetchPromis = fetch("bad-scheme://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/products.json");//这个是不可用链接
//测试时上两行代码二选一即可
fetchPromis
.then(Response => (Response.json()))
.then(json => {
console.log(json[0].name);
})
.catch(Error => {
console.log(`获取产品列表失败${Error}`);
});

控制台输出:baked beans 或者
获取产品列表失败TypeError: Failed to fetch

阶段5

这个例子演示了如何使用async和await组成的异步函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
async function fetchProducts() {
try{
const Response = await fetch("https://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/products.json");
if(!Response.ok){
throw new Error(`HTTP请求错误${Response.status}`);
}
const json = Response.json();
return json;
} catch (Error) {
console.log(`无法获取产品列表${Error}`);
}
}
const promise = fetchProducts();
promise.then(json => {
console.log(json[0].name);
});

控制台输出:baked beans

例八

1
2
3
4
5
6
<label for="name">你的名字:</label>
<input type="text" name="name" id="name" value="Elyrene"/><br>
<label for="time">输入延迟:</label>
<input type="text" name="time" id="time" value="2000"/><br>
<div><button id="alarm">设置定时器</button></div><br>
<div id="output">请设置定时器</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
const name = document.querySelector("#name");
const time = document.querySelector("#time");
const output = document.querySelector("#output");
const button = document.querySelector("#alarm");

function alarm(person, delay) {
return new Promise((resolve, reject) => {
if (delay < 0){
throw new Error(`delay is not allowed`);
}
window.setTimeout(() => {
resolve(`Wake UP ${person}!`);
}, delay);
});
}

button.addEventListener("click", async() => {
try{
const message = await alarm(name.value, time.value);
output.textContent = message;
} catch (Error) {
output.textContent = `Could not set Alarm ${Error}`;
};
});

一个简易的定时系统,利用Promise手动构造async异步函数。

例九(worker的使用)

前情提要

1
2
3
4
5
6
7
8
9
10
11
<label for="quota">素数个数:</label>
<input type="text" id="quota" name="quota" value="100000" />

<button id="generate">生成素数</button>
<button id="reload">重载</button>

<textarea rows="5" id="user-input" cols="62">
点击生成素数后在此处尝试输入文本
</textarea>

<div id="output"></div>
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
function generatePrimes (quota) {
function isPrime (n) {
for (let c = 2; c <= quota; ++c) {
if (n % c === 0) {
return false;
}
}
// console.log(n);
return true;
}
const primes = [];
const maximum = 100000000;
while (primes.length < quota) {
const candidate = Math.floor(Math.random() * (maximum + 1));
// console.log(candidate);
if (isPrime(candidate)) {
primes.push(candidate);
}
}
return primes;
}

document.querySelector("#generate").addEventListener("click", () => {
const quota = document.querySelector("#quota").value;
const primes = generatePrimes(quota);
document.querySelector(`#output`).textContent = `完成!已生成素数${quota}个`;
});

document.querySelector("#reload").addEventListener("click", () => {
document.location.reload();
});

这是一个效率极低的质数生成器。在点击生成质数按钮后,主线程被占用,无法在文本输入框输入信息。

使用Web workers

1
2
3
4
5
6
7
8
9
10
11
<label for="quota">素数个数:</label>
<input type="text" id="quota" name="quota" value="100000" />

<button id="generate">生成素数</button>
<button id="reload">重载</button>

<textarea rows="5" id="user-input" cols="62">
点击生成素数后在此处尝试输入文本
</textarea>

<div id="output"></div>

注:首先,记得在head中添加<script type="text/javascript" src="main.js" defer></script>。其次,要运行此案例,必须运行一个本地web服务器。因为file://URLs不允许加载workers。如果是VsCode编辑器的话,可以安装一个名为live serve的插件解决该问题。

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
//main.js部分
const worker = new Worker('./generate.js');

document.querySelector("#generate").addEventListener("click", () => {
const quota = document.querySelector("#quota").value;
worker.postMessage({
command: "gernerate",
quota: quota,
});
});

worker.addEventListener("message", message => {
document.querySelector("#output").textContent =
`Finish gernerate ${message.data} primes`;
});

document.querySelector("#reload").addEventListener("click", () => {
document.querySelector("#user-input").value =
`按下按钮后,尝试在此处输入文本`;
document.location.reload();
});

//generate.js部分
addEventListener("message", Message => {
if(Message.data.command === "gernerate") {
generatePrimes(Message.data.quota);
}
});

function generatePrimes(quota) {
function isPrimes(n) {
for(let c = 2; c <= quota; ++c) {
if(n % c === 0) {
return false;
}
}
return true;
}

const primes = [];
const Maximum = 100000000;

while (primes.length < quota) {
const candidate = Math.floor(Math.random() * (Maximum + 1));
if (isPrimes(candidate)) {
primes.push(candidate);
}
}

postMessage(primes.length);
}

在这个案例中,我们把这个效率极低的质数生成器丢给worker脚本去运算。generate.js线程与主线程是并行的,互不干扰,因此在点击生成质数按钮后,仍然可以在文本框内键入文字。

例十

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<h1>Fetch starting point</h1>

<form>
<label for="verse-choose">Choose a verse</label>
<select id="verse-choose" name="verse-choose">
<option>Verse 1</option>
<option>Verse 2</option>
<option>Verse 3</option>
<option>Verse 4</option>
</select>
</form>

<h2>The Conqueror Worm, <em>Edgar Allen Poe, 1843</em></h2>

<pre></pre>
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
const verseChoose = document.querySelector(`select`);
const poemDisplay = document.querySelector(`pre`);

verseChoose.addEventListener(`change`, () => {
const verse = verseChoose.value;
updateDispaly(verse);
});

function updateDispaly(verse) {
verse = verse.replace(' ','').toLowerCase();
const url = `${verse}.txt`;

fetch(url)
.then((Response) => {
if (!Response.ok) {
throw new Error(`Http错误${Response.status}`);
}
return Response.text();
})
.then((text) => poemDisplay.textContent = text)
.catch((Error) => (poemDisplay.textContent = `获取诗歌失败:${Error}`));
}

updateDispaly("Verse 1");
verseChoose.value = "Verse 1";

一个简单的诗歌显示网页,有三个.txt文件没有在这里给出。

注:同例九一样,需要安装live serve插件运行。

技能测试

测试一

固定页面代码

1
2
3
4
5
6
7
8
9
10
11
12
13
<h1>Image gallery example</h1>

<div class="full-img">
<img class="displayed-img" src="images/pic1.jpg" alt="Closeup of a human eye">
<div class="overlay"></div>
<button class="dark">Darken</button>
</div>

<div class="thumb-bar">


</div>
<script src="main.js"></script>
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
h1 {
font-family: helvetica, arial, sans-serif;
text-align: center;
}

body {
width: 640px;
margin: 0 auto;
}

.full-img {
position: relative;
display: block;
width: 640px;
height: 480px;
}

.overlay {
position: absolute;
top: 0;
left: 0;
width: 640px;
height: 480px;
background-color: rgba(0,0,0,0);
}

button {
border: 0;
background: rgba(150,150,150,0.6);
text-shadow: 1px 1px 1px white;
border: 1px solid #999;
position: absolute;
cursor: pointer;
top: 2px;
left: 2px;
}

.thumb-bar img {
display: block;
width: 20%;
float: left;
cursor: pointer;
}

我的答案

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
const displayedImage = document.querySelector('.displayed-img');
const thumbBar = document.querySelector('.thumb-bar');

const btn = document.querySelector('button');
const overlay = document.querySelector('.overlay');

const controller = new AbortController();

/* Declaring the array of image filenames */
//const image = [ //优化前代码
const images = [ //优化后代码
"pic1.jpg:Closeup of a human eye",
"pic2.jpg:Some image-2",
"pic3.jpg:Some image-3",
"pic4.jpg:Some image-4",
"pic5.jpg:Some image-5",
];
/* Declaring the alternative text for each image file */

/* Looping through images */
//for (let i = 0; i < 5; i++) { //优化前代码
for (const image of images) { //优化后代码
const newImage = document.createElement('img');
//const imageinfo = image[i].split(":"); //优化前代码
const imageinfo = image.split(":"); //优化后代码
newImage.setAttribute('src', `images/${imageinfo[0]}`);
newImage.setAttribute('alt', `images/${imageinfo[1]}`);
thumbBar.appendChild(newImage);
newImage.addEventListener("click", () => {
displayedImage.setAttribute("src", `${newImage.getAttribute("src")}`);
displayedImage.setAttribute("alt", `${newImage.getAttribute("alt")}`);
},{ signal:controller.signal});
};
/* Wiring up the Darken/Lighten button */

btn.addEventListener("click", () => {
const darkorlight = btn.getAttribute("class");
if (darkorlight === "dark") {
btn.setAttribute("class", `light`);
btn.textContent = `Lighten`;
overlay.style.backgroundColor = `rgba(0,0,0,0.5)`;
} else {
btn.setAttribute("class", `dark`);
btn.textContent = `Darken`;
overlay.style.backgroundColor = `rgba(0,0,0,0)`;
};
},{ signal:controller.signal });

参考答案

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
const displayedImage = document.querySelector('.displayed-img');
const thumbBar = document.querySelector('.thumb-bar');

const btn = document.querySelector('button');
const overlay = document.querySelector('.overlay');

/* Declaring the array of image filenames */

const images = ['pic1.jpg', `pic2.jpg`, `pic3.jpg`, `pic4.jpg`, `pic5.jpg`];
const alts = {
'pic1.jpg' : 'Closeup of a human eye',
'pic2.jpg' : 'Rock that looks like a wave',
'pic3.jpg' : 'Purple and white pansies',
'pic4.jpg' : 'Section of wall from a pharoah\'s tomb',
'pic5.jpg' : 'Large moth on a leaf'
}

/* Looping through images */

for (const image of images) { //遍历images(数据源)文件夹,将值赋予给image(接收容器);
const newImage = document.createElement('img');
newImage.setAttribute('src', `images/${image}`);
newImage.setAttribute('alt', alts[image]);
thumbBar.appendChild(newImage);
newImage.addEventListener('click', e => {
displayedImage.src = e.target.src;
displayedImage.alt = e.target.alt;
});
}

/* Wiring up the Darken/Lighten button */

btn.addEventListener('click', () => {
const btnClass = btn.getAttribute('class');
if (btnClass === 'dark') {
btn.setAttribute('class','light');
btn.textContent = 'Lighten';
overlay.style.backgroundColor = 'rgba(0,0,0,0.5)';
} else {
btn.setAttribute('class','dark');
btn.textContent = 'Darken';
overlay.style.backgroundColor = 'rgba(0,0,0,0)';
}
});

结果:一个简易的图片库

测试二

页面固定代码

1
<section class="preview"></section>

我的答案

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
const section = document.querySelector('section');

let para1 = document.createElement('p');
let para2 = document.createElement('p');
let motherInfo = 'The mother cats are called ';
let kittenInfo;
const requestURL = 'https://mdn.github.io/learning-area/javascript/oojs/tasks/json/sample.json';

fetch(requestURL)
.then(response => response.text())
.then(text => displayCatInfo(text))

function displayCatInfo(catString) {
let total = 0;
let male = 0;

// Add your code here
const catsInfo = JSON.parse(catString);
let i = 0;
for (const catInfo of catsInfo) {
i++;
// console.log(i);
// console.log(catsInfo.length);
// console.log(catInfo.kittens);
for(const kidInfo of catInfo.kittens){
total += 1;
if (kidInfo.gender === "m") {
male++;
}
}
if (i < catsInfo.length - 1) {
motherInfo += `${catInfo.name},`;
} else if (i === catsInfo.length - 1){
motherInfo += `${catInfo.name} `
} else {
motherInfo += `and ${catInfo.name}.`
}

total += 1;
}
// console.log(catsInfo);
// console.log(male);
// console.log(total);
let female = total - male;
kittenInfo = `小猫中有${male}只公猫和${female}只母猫`
// Don't edit the code below here!

para1.textContent = motherInfo;
para2.textContent = kittenInfo;
}

section.appendChild(para1);
section.appendChild(para2);

JSON文件

这里附上JSON代码,代码中不必加入

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
[
{
"name" : "Lindy",
"breed" : "Cymric",
"color" : "white",
"kittens" : [
{
"name" : "Percy",
"gender" : "m"
},
{
"name" : "Thea",
"gender" : "f"
},
{
"name" : "Annis",
"gender" : "f"
}
]
},
{
"name" : "Mina",
"breed" : "Aphrodite Giant",
"color" : "ginger",
"kittens" : [
{
"name" : "Doris",
"gender" : "f"
},
{
"name" : "Pickle",
"gender" : "f"
},
{
"name" : "Max",
"gender" : "m"
}
]
},
{
"name" : "Antonia",
"breed" : "Ocicat",
"color" : "leopard spotted",
"kittens" : [
{
"name" : "Bridget",
"gender" : "f"
},
{
"name" : "Randolph",
"gender" : "m"
}
]
}
]

浏览器输出:

  • The mother cats are called Lindy,Mina and Antonia.
  • 小猫中有3只公猫和8只母猫

测试三

固定页面代码

1
2
3
4
5
6
7
<h1>My shopping list</h1>
<form>
<label for="item">Enter a new item:</label>
<input type="text" name="item" id="item">
<button>Add item</button>
</form>
<ul></ul>

我的答案

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
const input = document.querySelector(`#item`);
const button = document.querySelector(`button`);
const list = document.querySelector(`ul`);

button.addEventListener(`click`, (event) => {
event.preventDefault();
const listItem = document.createElement(`li`);
const listBtn = document.createElement(`button`);
const listspan = document.createElement(`span`);

listItem.textContent = input.value;
listBtn.textContent = `delet`;

input.value = ``;
input.focus();

listspan.appendChild(listBtn);
listItem.appendChild(listspan);

listBtn.addEventListener("click", () => {
list.removeChild(listItem);
});

list.appendChild(listItem);
});

参考答案

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
const list = document.querySelector('ul');
const input = document.querySelector('input');
const button = document.querySelector('button');

button.addEventListener('click', (event) => {
event.preventDefault();

const myItem = input.value;
input.value = '';

const listItem = document.createElement('li');
const listText = document.createElement('span');
const listBtn = document.createElement('button');

listItem.appendChild(listText);
listText.textContent = myItem;
listItem.appendChild(listBtn);
listBtn.textContent = 'Delete';
list.appendChild(listItem);

listBtn.addEventListener('click', () => {
list.removeChild(listItem);
});

input.focus();
});

一个简易的动态的购物单

某些疑问的总结

  1. 什么时候需要用引号?
    • 是文本,就加引号(“hello”, ‘123’)
    • 是代号,就不加引号(变量名、函数名、普通的对象属性名)
    • 方括号里,认文本加引号(obj[“name”]),认变量不加引号(obj[varName])
    • 有变量要插,有回车要换,用反引号(`你好${name}`

本篇流水账已结束更新