|
20 | 20 | <h1>輸入尋找的關鍵文字</h1> |
21 | 21 | <input class="form-control" type="text" id="search" class="search" placeholder="詩句 詩名 詩人"> |
22 | 22 | <ul class="list-group" id="suggestions"> |
23 | | - <li class="list-group-item">First item</li> |
24 | 23 | </ul> |
25 | 24 |
|
26 | 25 | </div> |
@@ -88,25 +87,46 @@ <h1>輸入尋找的關鍵文字</h1> |
88 | 87 | const title_ok = each_item.title.match(regex) |
89 | 88 | const text_ok = each_item.detail_text.match(regex) |
90 | 89 | //console.log(name_ok || title_ok || text_ok) |
91 | | - |
| 90 | + |
92 | 91 | console.log(name_ok) |
93 | 92 | console.log(title_ok) |
94 | 93 | console.log(text_ok) |
95 | 94 |
|
96 | 95 | return name_ok || title_ok || text_ok |
97 | | - |
| 96 | + |
98 | 97 | //return null |
99 | 98 | }) |
100 | 99 | //console.log(result_data) |
101 | 100 | return result_data |
102 | 101 | } |
103 | 102 |
|
104 | | - function display_mydata() { |
105 | | - var keyword = this.value |
106 | | - var filter_results = filter_mydata(keyword, my_data) |
107 | | - console.log(filter_results) |
| 103 | + function highlight_html(keyword, data) { |
| 104 | + const regex = new RegExp(keyword, 'gi'); //正則找出匹配的詩句 |
| 105 | + let html = data.map(poet => { |
| 106 | + // 替換高亮的標籤 |
| 107 | + const text = poet.detail_text.replace(regex, '<span class="hl">' + keyword + '</span>'); |
| 108 | + const title = poet.title.replace(regex, '<span class="hl">' + keyword + '</span>'); |
| 109 | + const author = poet.detail_author[0].replace(regex, '<span class="hl">' + keyword + '</span>'); |
| 110 | + // 構造 HTML 值 |
| 111 | + return ` |
| 112 | + <li class="list-group-item"> |
| 113 | + <span class="poet">${text}</span> |
| 114 | + <span class="title">${title} - ${author}</span> |
| 115 | + </li> |
| 116 | + `; |
| 117 | + }).join(''); |
| 118 | + |
| 119 | + return html; |
108 | 120 |
|
| 121 | + } |
109 | 122 |
|
| 123 | + function display_mydata() { |
| 124 | + var keyword = this.value |
| 125 | + const res = filter_mydata(keyword, my_data) |
| 126 | + //console.log(filter_results) |
| 127 | + const html = highlight_html(keyword, res) |
| 128 | + //console.log(html); |
| 129 | + suggestions.innerHTML = html; |
110 | 130 | } |
111 | 131 |
|
112 | 132 | var search = document.querySelector('#search') |
|
0 commit comments