如何在纯 Javascript 中搜索更复杂的列表项

How to search more complex list items in pure Javascript

目前,我正在尝试使用 javascript 为项目创建一个搜索字段,但出于某种原因,我的搜索代码无法正常工作。我将此归因于列表项的复杂性,至此,在下面的列表中搜索 H3 标签的正确 Javascript 代码是什么:

 <ul class="results" list-style: none>
        <li class="result">
            <div class="container">
                    <div class='headline'>
                        <h3>a list item</h3>
                    </div>
            </div>
        </li>
        <li class="result">
            <div class="container">
                    <div class='headline'>
                        <h3>a list item 2</h3>
                    </div>
            </div>
        </li>
        <li class="result">
            <div class="container">
                    <div class='headline'>
                        <h3>a list item 3</h3>
                    </div>
            </div>
        </li>
    </ul>

必须有更好的定义:“我将此归因于列表项的复杂性,就这一点而言,搜索 H3 标签的正确 Javascript 代码是什么下面的列表:

最基本的搜索:

document.querySelectorAll('h3'); // -> returning a nodelist with all the h3 elements in the dom

如果您需要添加更多“复杂性”,只需更改 ('selector')

中的选择器

否则,请编辑您的问题,使其更精确,例如示例输出。

更新:

所以如果我正确理解你的意思那么一个非常非常通用的例子来证明我猜你的意思

const getH3 = document.querySelectorAll('ul.results h3'); // here we get all the h3 inside the ul

// let us assume that in our "seach box" the term was '2' for example
const term = '2';

// what to do now? Since we got all our h3 already inside a const we can just go through all of them to check if the term is there, like for example with a forEach

// also creating here an array to push in all the matches
let matches = [];
getH3.forEach(h3 => {
      if (h3.textContent.includes(term)) matches.push(h3); // here we push in if our search term was found inside the textContent of an h3 using the string method "includes"
      // ofc you can also directly just push the found textContent or also both .-.
});

console.log(matches); // output: [h3]
console.log(matches[0].textContent); // output: a list item 2

更新 2 所以这应该回答关于这个主题的一般问题:

这里是带注释的代码:

// for simplicity i will stick with the example from before with my 2 since its a pretty simple term :)
    // so we doing the same things as before but with some modification

    const getH3 = document.querySelectorAll('ul.results h3'); // keep in mind that this script should be executed
    // after the dom loaded, otherwise getH3 will be [] empty

    // getting our input field which i added to the html with the id
    const search = document.getElementById('search'); // here the same with the loading

    // so now we have several ways to make our "searching" for probably all ways we need some event
    // this could be everytime we type something or when we click on a button etc.
    // we will use the "input" or "change" event

    // so adding the Eventlistener, could be achieved in two ways, i will use the addEventListener method
    search.addEventListener('input', () => {
        // everytime there is an input in the input element this function will be called

        // since you dont need to work with the element, we dont need to save what we found, we will just make them the only ones left on the screen

        // this can be achieved (in my opinion!) with giving or removing a class which makes them disappear or appear
        // so we added a small css class with display:none

        // now again we go through all h3

        // so now it gets a bit weird since we used the h3, i will explain the other way underneath
        getH3.forEach(h3 => {
            if (h3.textContent.includes(search.value)) { // if the h3 should be displayed
                h3.parentElement.parentElement.parentElement.classList.remove('invis') // dom traversing to the li element which holds the h3 to remove the class in case it was there

            } else { // if the h3 shouldnt be displayed
                h3.parentElement.parentElement.parentElement.classList.add('invis') // adding the class to the li so it disappear
            }
        });

        /*
        alternative we could also go through all the li or just use document.querySelector('ul.results>li')
        to get all the li
        like:
        const getLi = document.querySelectorAll('ul.results>li');

        getLi.forEach(li =>{
            ...
        })
        */
    })

in html 添加到 ul:

<input id="search" type="text"> <!-- search box -->

并且在 css 中 class:

.invis {
      display: none;
}

这里有一个示例片段,您可以 运行 自己看看它现在是如何工作的:

const getH3 = document.querySelectorAll('ul.results h3');

        const search = document.getElementById('search');

        search.addEventListener('input', () => {
            getH3.forEach(h3 => {
                if (h3.textContent.includes(search.value)) h3.parentElement.parentElement.parentElement.classList.remove('invis');
                else h3.parentElement.parentElement.parentElement.classList.add('invis');
            });
        })
.invis {
     display: none;
 }
<!DOCTYPE html>
<html lang="de">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Searching</title>
</head>

<body>
    <input id="search" type="text"> <!-- search box -->
    <ul class="results" list-style: none>
        <li class="result">
            <div class="container">
                <div class='headline'>
                    <h3>a list item</h3>
                </div>
            </div>
        </li>
        <li class="result">
            <div class="container">
                <div class='headline'>
                    <h3>a list item 2</h3>
                </div>
            </div>
        </li>
        <li class="result">
            <div class="container">
                <div class='headline'>
                    <h3>a list item 3</h3>
                </div>
            </div>
        </li>
    </ul>
</body>

</html>