-
Notifications
You must be signed in to change notification settings - Fork 537
/
index-SOYAINE.html
66 lines (57 loc) · 2.1 KB
/
index-SOYAINE.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
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ajax Type Ahead 👀</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<form class="search-form">
<input type="text" class="search" placeholder="诗句 诗名 诗人">
<ul class="suggestions">
<li>输入词句,找一首诗</li>
<li></li>
</ul>
</form>
<script>
// const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';
const endpoint = 'https://gist.githubusercontent.com/soyaine/81399bb2b24ca1bb5313e1985533c640/raw/bdf7df2cbcf70706c4a5e51a7dfb8c933ed78878/TangPoetry.json';
const poetrys = [];
fetch(endpoint)
.then(blob => blob.json())
.then(data => poetrys.push(...data));
function findMatches(wordToMatch, poetrys) {
return poetrys.filter(poet => {
// 正则找出匹配的诗句
const regex = new RegExp(wordToMatch, 'gi');
const author = poet.detail_author.join('');
// console.log(author);
return poet.detail_text.match(regex) || poet.title.match(regex) || author.match(regex);
});
}
function displayMatches() {
const matches = findMatches(this.value, poetrys);
const regex = new RegExp(this.value, 'gi');
const html = matches.map(poet => {
// 替换高亮的标签
const text = poet.detail_text.replace(regex, `<span class="hl">${ this.value }</span>`);
const title = poet.title.replace(regex, `<span class="hl">${ this.value }</span>`)
// 构造 HTML 值
return `
<li>
<span class="poet">${ text }</span>
<span class="title">${ title } - ${ poet.detail_author[0] }</span>
</li>
`;
}).join('');
// console.log(html);
suggestions.innerHTML = html;
}
const search = document.querySelector('.search');
const suggestions = document.querySelector('.suggestions');
search.addEventListener('change', displayMatches);
search.addEventListener('keyup', displayMatches);
// console.log(poetrys);
</script>
</body>
</html>