我正在嘗試為搜索字串的每個單詞搜索多個字串,并且只顯示包含它的每個單詞的字串。
到目前為止,我設法構建了一個整體查找字串的搜索工具,但我想單獨搜索每個單詞,可能通過將搜索字串拆分為字串陣列。
在下面的示例中,搜索“first”會顯示第一段,但搜索“This first”不會顯示任何內容,因為在段落中搜索的是整個詞,而不是單獨搜索單詞“This”和“first”。
我怎樣才能做到這一點?
let search = document.getElementsByTagName("input")[0];
search.addEventListener("input", function() {
let s = search.value;
for (let e of search.nextElementSibling.children) {
if (e.textContent.search(s) == -1) {
e.style.display = "none";
} else if (e.style.display == "none") {
e.style.display = "block";
}
}
});
<html>
<head>
<title>Title</title>
</head>
<body>
<input type="search">
<div>
<p>This is the first string.</p>
<p>This is the second string.</p>
<p>This is the third string.</p>
</div>
</body>
uj5u.com熱心網友回復:
您可以在空格上拆分搜索字串并使用someandincludes來確定每個字串中是否有任何單詞
let search = document.getElementsByTagName("input")[0];
search.addEventListener("input", function() {
let s = search.value.split(" ");
for (let e of search.nextElementSibling.children) {
if (!s.some(x => e.textContent.includes(x)) ) {
e.style.display = "none";
} else if (e.style.display == "none") {
e.style.display = "block";
}
}
});
<html>
<head>
<title>Title</title>
</head>
<body>
<input type="search">
<div>
<p>This is the first string.</p>
<p>This is the second string.</p>
<p>This is the third string.</p>
</div>
</body>
uj5u.com熱心網友回復:
您可以按空格拆分文本,并檢查是否所有單詞都包含 with 與Array#every一起Array#includes。
let search = document.querySelector("input");
search.addEventListener("input", function() {
let s = search.value.split(/\s /);
for (let e of search.nextElementSibling.children) {
let words = e.textContent.split(/\s /);
if (!s.every(x => words.includes(x))) {
e.style.display = "none";
} else {
e.style.display = "block";
}
}
});
<input type="search">
<div>
<p>This is the first string.</p>
<p>This is the second string.</p>
<p>This is the third string.</p>
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/416662.html
標籤:
