javascript - 如何使用 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
附加到数组,命名为li
thingContainer
storage
因此,当在最后一段代码中(在 findButton 上单击)时,我将某个索引(例如 1)放入方括号中 - 它可以工作,但是当我以这里的方式这样做时 - 它没有。你能帮热修一下吗?
将感谢任何答案。生长激素
解决方案
请看下面的片段。
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>
推荐阅读
- javascript - Javascript - 当 ID 添加到同一页面上 url 的末尾时,window.location.href 和 window.location.replace 不起作用
- java - java - 调用自定义火花UDF时如何解决Java中的NoSuchMethodException
- html - 使用 CSS GRID 为什么我会遇到这个差距?
- c++ - 优先队列中的比较器功能
- dll - 如何在 .dll (Dymola) 中使用 ModelicaError() 函数
- python - (Pathlib) Root + 'foldername' throwing TypeError: unsupported operand type(s) for +: 'WindowsPath' and 'str'
- .htaccess - 如何在 htaccess 中添加 http/2 标头以推送文件
- git - 多分支 Jenkins 管道停止扫描所有分支中的 Jenkins 文件
- python-3.x - 使用 cv2.dnn.readNetFromTorch 时出错
- javascript - 来自字符串的完美 JSON 格式