Visitar URL original
0502 · soyaine/JavaScript30@5651cc0 · GitHub
Skip to content

Commit 5651cc0

Browse files
committed
0502
1 parent 4224064 commit 5651cc0

2 files changed

Lines changed: 29 additions & 8 deletions

File tree

‎06 - Type Ahead/js30-06.css‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,5 +3,6 @@ body{
33
}
44

55
.hl {
6-
background:hsla(193, 37%, 64%, 0.65);
6+
/*background:hsla(193, 37%, 64%, 0.65);*/
7+
background: #ff6666
78
}

‎06 - Type Ahead/js30-06.html‎

Lines changed: 27 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@
2020
<h1>輸入尋找的關鍵文字</h1>
2121
<input class="form-control" type="text" id="search" class="search" placeholder="詩句 詩名 詩人">
2222
<ul class="list-group" id="suggestions">
23-
<li class="list-group-item">First item</li>
2423
</ul>
2524

2625
</div>
@@ -88,25 +87,46 @@ <h1>輸入尋找的關鍵文字</h1>
8887
const title_ok = each_item.title.match(regex)
8988
const text_ok = each_item.detail_text.match(regex)
9089
//console.log(name_ok || title_ok || text_ok)
91-
90+
9291
console.log(name_ok)
9392
console.log(title_ok)
9493
console.log(text_ok)
9594

9695
return name_ok || title_ok || text_ok
97-
96+
9897
//return null
9998
})
10099
//console.log(result_data)
101100
return result_data
102101
}
103102

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;
108120

121+
}
109122

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;
110130
}
111131

112132
var search = document.querySelector('#search')

0 commit comments

Comments
 (0)