我有一些内容,其中包含元数据和上方的搜索字段。在该字段中键入内容时,它应该向我显示一个链接列表,该链接列表使我可以向下滚动页面至内容。一切正常,除了我必须在链接上单击两次以触发它们。
我改为使用document.createElement
进行了快速测试,这看起来效果更好,但是我不确定如何使用所需的嵌套内容来进行测试。我认为使用模板字符串和innerHTML
是一种不错的方法,但是以某种方式,那些动态添加的链接需要双击。
HTML
<input type="text" class="search" placeholder="Service" id="serviceInput">
<div id="serviceInputResults"></div>
<hr>
<div class="sections">
<div class="accordion-item">
<div class="accordion-title">
<h5>My first Headline</h5>
</div>
<div class="accordion-content" data-tab-content id="deeplink1" data-keywords="somedata, moredata, test, abc, asd" data-headline="my first headline">
lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum
</div>
</div>
<div class="accordion-item">
<div class="accordion-title">
<h5>My second Headline</h5>
</div>
<div class="accordion-content" data-tab-content id="deeplink2" data-keywords="blub, moredata, test, abc, asd" data-headline="my second headline">
lorem ipsum lorem ipsum
</div>
</div>
<div class="accordion-item">
<div class="accordion-title">
<h5>My third Headline</h5>
</div>
<div class="accordion-content" data-tab-content id="deeplink3" data-keywords="another, moredata, test, abc, asd" data-headline="my third headline">
lorem ipsum lorem ipsum asd asd asd asd
</div>
</div>
</div>
JAVASCRIPT
// Get all the raw data
const items = [...document.querySelectorAll(".accordion-content")];
const data = items.filter(item => item.dataset.keywords).map(item => {
return {
id: item.id,
keywords: item.dataset.keywords,
headline: item.dataset.headline
};
});
// filter matches
function findMatches(data, searchString) {
if (!searchString) return;
return data.filter(item => {
const regex = new RegExp(searchString, "gi");
return item.keywords.match(regex);
});
}
// render HTML
function displayMatches() {
const items = findMatches(data, this.value);
if (items) {
serviceInputResults.innerHTML = `<ul>
${items
.map(
item =>
`<li><a class="serviceInputResults__link" href="#${item.id}">${
item.headline
}</a></li>`
)
.join("")}
</ul>`;
} else {
serviceInputResults.innerHTML = "";
}
}
// Get Search Input
const input = document.querySelector("#serviceInput");
const serviceInputResults = document.querySelector("#serviceInputResults");
input.addEventListener("change", displayMatches);
input.addEventListener("keyup", displayMatches);
这是一个jsfiddle: https://jsfiddle.net/1jmwgp8b/