|
| 1 | +<!DOCTYPE html> |
| 2 | +<html lang="en"> |
| 3 | +<head> |
| 4 | + <meta charset="UTF-8"> |
| 5 | + <title>Type Ahead 👀</title> |
| 6 | + <link rel="stylesheet" href="style.css"> |
| 7 | +</head> |
| 8 | +<body> |
| 9 | + |
| 10 | + <form class="search-form"> |
| 11 | + <input type="text" class="search" placeholder="诗句 抑或 诗名"> |
| 12 | + <ul class="suggestions"> |
| 13 | + <li>输入词句,找一首诗</li> |
| 14 | + <li></li> |
| 15 | + </ul> |
| 16 | + </form> |
| 17 | +<script> |
| 18 | +// const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json'; |
| 19 | + |
| 20 | + const endpoint = 'https://raw.githubusercontent.com/soyaine/FE-Practice/gh-pages/TangPoetryCut.json'; |
| 21 | + |
| 22 | + |
| 23 | + const poetrys = []; |
| 24 | +fetch(endpoint) |
| 25 | + .then(blob => blob.json()) |
| 26 | + .then(data => poetrys.push(...data)); |
| 27 | + |
| 28 | + function findMatches( wordToMatch, poetrys) { |
| 29 | + return poetrys.filter(poet => { |
| 30 | + // 找出匹配的诗句 |
| 31 | + const regex = new RegExp(wordToMatch, 'gi'); |
| 32 | + return poet.detail_text.match(regex) || poet.title.match(regex); |
| 33 | + }); |
| 34 | + } |
| 35 | + |
| 36 | +// function displayMatches() { |
| 37 | +// const matches = findMatches(this.value, poetrys); |
| 38 | +// suggestions.innerHTML = ""; |
| 39 | +// matches.forEach(poet => { |
| 40 | +// const li = document.createElement('li'); |
| 41 | +// li.textContent = poet.detail_text; |
| 42 | +//// .replace('。', '。'+'⁣'); |
| 43 | +// suggestions.appendChild(li); |
| 44 | +// console.log(poet.detail_text) |
| 45 | +// }); |
| 46 | +// } |
| 47 | + |
| 48 | + function displayMatches() { |
| 49 | + const matches = findMatches(this.value, poetrys); |
| 50 | + const html = matches.map( poet => { |
| 51 | + const text = poet.detail_text.replace(this.value, `<span class="hl">${ this.value }</span>`); |
| 52 | + return ` |
| 53 | + <li> |
| 54 | + <span class="poet">${ text }</span> |
| 55 | + </li> |
| 56 | + `; |
| 57 | + }).join(''); |
| 58 | +// <span class="info"> |
| 59 | +// <span class="title">${ poet.title }</span> |
| 60 | +// <span class="author">${ poet.detail_author[0] }</span> |
| 61 | +// </span> |
| 62 | + console.log(html); |
| 63 | + suggestions.innerHTML = html; |
| 64 | + } |
| 65 | + |
| 66 | + const search = document.querySelector('.search'); |
| 67 | + const suggestions = document.querySelector('.suggestions'); |
| 68 | + |
| 69 | + search.addEventListener('change', displayMatches); |
| 70 | + search.addEventListener('keyup', displayMatches); |
| 71 | + |
| 72 | +// console.log(cities); |
| 73 | + </script> |
| 74 | + </body> |
| 75 | +</html> |
| 76 | + |
| 77 | + |
| 78 | + |
| 79 | + |
| 80 | + |
| 81 | + |
| 82 | + |
| 83 | + |
0 commit comments