简体   繁体   English

如何制作一个有效的搜索栏

[英]How to make a functioning search bar

I'm trying to make a functioning searchbar in javascript,that when you press enter, will delete all the content of the page while only showing the elements that I'm searching for.我正在尝试在 javascript 中创建一个功能强大的搜索栏,当您按下 Enter 键时,将删除页面的所有内容,同时只显示我正在搜索的元素。 The elements I just mentioned are in order list.我刚刚提到的元素在订单列表中。

You could have 2 lists.你可以有 2 个列表。 One for all of the elements and the other one for filtered ones.一个用于所有元素,另一个用于过滤的元素。

You could use Array.filter to narrow the list down to items that don't meet the search criteria, and then loop over those elements, and set those items style.display to none.您可以使用 Array.filter 将列表缩小到不符合搜索条件的项目,然后遍历这些元素,并将这些项目 style.display 设置为 none。

Something like this (Im not sure how/what the elements of the ordered list are)像这样的东西(我不确定有序列表的元素是如何/是什么)

//You may have to change this to reflect the actual structure your list
let orderedList = Array.from(document.querySelectorAll('ol>li'))
// get the
let query = document.getElementById('search').value.toLowerCase()
orderedList.filter(element=>{
  // get the text in the list and compare it to the query
  let elementText = element.innerText.toLowerCase()
  let matchesQuery = elementText === query || elementText.startsWith(query) || elementText.contains(query)
  //return the ones that don't match
  return !matchesQuery
}).forEach(element=>{
  //now loop over the ones that dont match
  element.style.display = 'none'
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM