【问题标题】:Hide h4 on search在搜索中隐藏 h4
【发布时间】:2020-05-27 18:34:45
【问题描述】:

我想在搜索文本时隐藏 h4 标题。我可以进行搜索,但也想隐藏 h4。

<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name">

<h4>Name List 1</h4>
<ol id="myUL">
  <li><a href="#">Adele</a></li>
  <li><a href="#">Bob</a></li>
</ol>

<h4>Name List 2</h4>
<ol id="myUL2">
  <li><a href="#">Agnes</a></li>
  <li><a href="#">Billy</a></li>
</ol>

<h4>Name List 3</h4>
<ol id="myUL3">
  <li><a href="#">Anim</a></li>
  <li><a href="#">Bitto</a></li>
  <li><a href="#">Cindy</a></li>
</ol>

我有如下所述的搜索选项。


function myFunction() {
    var input, filter, ol, li, a, i, txtValue;
    input = document.getElementById("myInput");
    filter = input.value.toUpperCase();
    li = document.querySelectorAll("ol li");

    for (i = 0; i < li.length; i++) {
        a = li[i].getElementsByTagName("a")[0];
        txtValue = a.textContent || a.innerText;
        if (txtValue.toUpperCase().indexOf(filter) > -1) {
            li[i].style.display = "";
        } else {
            li[i].style.display = "none";
        }
    }
}

【问题讨论】:

  • 您只想隐藏那些没有找到结果的 h4 标题?
  • @Aish 你只想隐藏&lt;h4&gt; 或包括最后一个&lt;ol&gt; 的完整块?
  • 实际完成,脚本全部隐藏。但不是 h4
  • imgur.com/jDXECgH 这是我搜索得到的回报,我想隐藏姓名列表 1、2、3
  • 你想隐藏所有 h4 吗?只有那些没有结果的h4?

标签: javascript html search


【解决方案1】:

function myFunction() {
    var input, filter, ol, li, a, i, txtValue;
    input = document.getElementById("myInput");
    filter = input.value.toUpperCase();
    li = document.querySelectorAll("ol li");
    var parent;
    var sibiling;
    for (i = 0; i < li.length; i++) {
    
        a = li[i].getElementsByTagName("a")[0];
        txtValue = a.textContent || a.innerText;
        if (txtValue.toUpperCase().indexOf(filter) > -1) {
            li[i].style.display = "";
         Array.prototype.forEach.call(document.getElementsByTagName("h4"), function(el) {
                    el.style.display = '';
                });
        } else {
            li[i].style.display = "none";
                                      Array.prototype.forEach.call(document.getElementsByTagName("h4"), function(el) {
                    el.style.display = 'none';
                });
        }
    }
}
<html>
<body>
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name">

<h4>Name List 1</h4>
<ol id="myUL">
  <li><a href="#">Adele</a></li>
  <li><a href="#">Bob</a></li>
</ol>

<h4>Name List 2</h4>
<ol id="myUL2">
  <li><a href="#">Agnes</a></li>
  <li><a href="#">Billy</a></li>
</ol>

<h4>Name List 3</h4>
<ol id="myUL3">
  <li><a href="#">Anim</a></li>
  <li><a href="#">Bitto</a></li>
  <li><a href="#">Cindy</a></li>
</ol>
</body>
</html>

检查这是否符合预期。

【讨论】:

    猜你喜欢
    • 2018-03-31
    • 1970-01-01
    • 2012-04-25
    • 2022-07-21
    • 2013-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多