【问题标题】:How to keep items hidden after clean search?干净搜索后如何隐藏项目?
【发布时间】:2020-07-08 20:50:22
【问题描述】:

我构建了一个常见问题页面并使用 JavaScript 实现了搜索功能。 所有项目列表最初都是隐藏的,当我在搜索栏中键入关键字时,结果会显示。 但是,在搜索栏中清空关键字后,我遇到了问题。

在我输入内容然后清空后,所有项目的列表仍然可见,但是,我想将它们隐藏起来。




我的 index.html.haml (这是一个很长的列表,所以我显示一些作为参考)

%input#myInput{:onkeyup => "findFAQ()", :placeholder => "Search for questions", :title => "Type keywords", :type => "text"}

%ul#faqall
      %li
        %button.hidden.faq-toggle-list Where can I apply?
        .highlight
          %div.hidden
            apply in person at your local office. We are looking forward to hearing from you!
      %li
        %button.hidden.faq-toggle-list When can I expect to hear back from you?
        .highlight
          %div.hidden
            we will contact you for an interview 
      %li
        %button.hidden.faq-toggle-list Do you have any jobs available?
        .highlight
          %div.hidden
            Yes! Please visit us at
      %li
        %button.hidden.faq-toggle-list Do I sign up online or come to the office?
        .highlight
          %div.hidden
            Yes! Please visit us
            
      %li
        %button.hidden.faq-toggle-list I want to work in a specific industry only, can you help me?
        .highlight
          %div.hidden
            We work across all industries and all verticals.

faq.js

function findFAQ() {
  var input, filter, ul, li, a, i, txtValue;
  
  input = document.getElementById("myInput");
  filter = input.value.toUpperCase();
  ul = document.getElementById("faqall");
  li = ul.getElementsByTagName("li");
  for (i = 0; i < li.length; i++) {
      
      a = li[i].getElementsByTagName("button")[0];
      txtValue = a.textContent || a.innerText;
      if (txtValue.toUpperCase().indexOf(filter) > -1) {
          a.style.display = "block";
          
          
      } else {
          a.style.display = "none";
          
      }
}
}

faq.scss

.hidden {
display: none;
}

【问题讨论】:

  • 我的建议是不要隐藏搜索背后的所有有用信息。用它来过滤
  • 这将是一种可能的方式。但是,我想保持这种方式,因为问答下面还有其他内容。我希望访问者能够在第一眼看到他们。如果我不隐藏那长长的问题列表(大约 50 个),访问者将不得不向下滚动一段时间才能看到其他内容。

标签: javascript haml


【解决方案1】:

只需更改下面的 if

if (txtValue.toUpperCase().indexOf(filter) > -1) {

  if (filter && txtValue.toUpperCase().indexOf(filter) > -1) {

它会起作用的

【讨论】:

  • 这就是我要找的。谢谢!!
  • 没问题,很高兴能帮上忙。但只是为了通知您 SO 在接受复选标记附近有“谢谢”反应。不鼓励在 cmets 中感谢,因为它约占 SO 上所有用户 cmets 的 20%,并且对其他读者没有用处。 :)
猜你喜欢
  • 1970-01-01
  • 2011-01-19
  • 1970-01-01
  • 1970-01-01
  • 2016-05-23
  • 1970-01-01
  • 2019-02-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多