首页 > 解决方案 > 如何使用 for 循环在 JavaScript 上制作搜索栏?

问题描述

我有以下 HTML 和 JS:

<body>

    <div class = "to_do_list">

            <div class = "add"></div>
            <div id = "delete"></div>
                
            <input id = "input" type = "text" name = "">

            <div id = "add_button"></div>

            <div class = "find"></div>
            <input id = "find_form" type = "text" placeholder = "Find">
            <button id = "find_button" type = "submit">Start</button>

            <div class = "thing_container"> </div>

    </div>
    
</body>
    let storage = [];

    addButton.onclick = () => {


       let newElement = document.createElement("li");

       newElement.style.background = 'purple';
       newElement.textContent = input.value;
       thingContainer.appendChild(newElement);

       storage.push(newElement);


   }

      findButton.onclick = () => {

        for (let i = 0; i < storage.length; i++) {

           if (storage[i].textContent.indexOf(find_form.value) >= 0) {
              storage[i].style.display = "block";
           }

           else {
              storage[i].style.display = "none";
          }
   } 

通过单击addButton代码创建一个li元素,将其中的文本附加到它,然后将元素input附加到数组,命名为lithingContainerstorage

因此,当在最后一段代码中(在 findButton 上单击)时,我将某个索引(例如 1)放入方括号中 - 它可以工作,但是当我以这里的方式这样做时 - 它没有。你能帮热修一下吗?

将感谢任何答案。生长激素

标签: javascripthtmlcss

解决方案


请看下面的片段。

let storage = [];
let addButton = document.getElementById('add_button');
let findButton = document.getElementById('find_button');
let thingContainer = document.getElementById('thing_container');

addButton.onclick = () => {
  let newElement = document.createElement("li");
  newElement.style.background = "purple";
  newElement.textContent = input.value;
  thingContainer.appendChild(newElement);
  storage.push(newElement);
};

findButton.onclick = () => {
  for (let i = 0; i < storage.length; i++) {
    if (storage[i].textContent.indexOf(find_form.value) >= 0) {
      storage[i].style.display = "block";
    } else {
      storage[i].style.display = "none";
    }
  }
};
<body>

    <div class = "to_do_list">

            <div class = "add"></div>
            <div id = "delete"></div>
                
            <input id = "input" type = "text" name = "">

            <button id = "add_button">Add</button>

            <div class = "find"></div>
            <input id = "find_form" type = "text" placeholder = "Find">
            <button id = "find_button" type = "submit">Start</button>

            <div id= "thing_container"></div>

    </div>
    
</body>


推荐阅读