【问题标题】:How to hide a element if input is empty?如果输入为空,如何隐藏元素?
【发布时间】:2022-01-24 19:18:32
【问题描述】:

我是一名学习 javascript 的学生,我正在尝试构建一个搜索功能。
我有多个带有图片的 html 图。我正在使用输入和 figcaptions 过滤数字。
我试图隐藏与输入值不匹配的数字。
但是我有一个图已经有一个 css display:none;。
当您搜索此特定图形时,它会弹出,但在输入再次为空后,该图形仍然可见。
我尝试使用obj.style.display = "" 和obj.style.display = "none" 重置css。 但这没有用。
简而言之,我的目标是隐藏一个图形,直到它与输入的值匹配,但如果输入为空,则应再次隐藏它。
任何帮助将不胜感激,谢谢!

// entire code can be found here: https://codepen.io/Yung_n-d/pen/mdwQGqX
//Javascript
function myFunction() {
    var input, filter, ul, li, a, i, txtValue, getSpecial;
    input = document.getElementById("myInput");
    filter = input.value.toUpperCase();
    ul = document.getElementById("background");
    li = ul.getElementsByTagName("figure");
    getSpecial = document.getElementsByClassName('special');
 
    for (i = 0; i < li.length; i++) {

        a = li[i].getElementsByTagName("figcaption")[0];
        txtValue = a.textContent || a.innerText;


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

            li[i].style.display = "";
            
        } else {
            li[i].style.display = "none";
            
        }
        if(filter == 0){
          getSpecial.style.display = "";
          
        }
    }
} 

//HTML
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Zoek workshops.." title="Type in a name">
<div id="background">
  <div id="gallery">
    <figure class="pic1 4-5 6-8 8-12 12+ Dans">
      <a href="workshopPages/dans/index.php">
      <img src="media/fotos/gallery/Dans.png" />
      <figcaption class="test">Dans</figcaption>
    </figure>
    <figure class="special" style="display: none;" id="8-12" class="pic10 4-5 6-8 8-12 12+ ckv">
      <a href="workshopPages/reeks/index.php">
      <img src="media/fotos/gallery/reeks.png" />
      <figcaption>Film</figcaption>
    </figure>
  </div>
</div>

【问题讨论】:

  • 能否请您包含所有相关的 HTML(不是 PHP),以便我们可以创建问题的工作示例
  • @RoryMcCrossan 我将所有 php 转换回普通 HTML。很抱歉给您带来不便。
  • #myInput 元素在哪里? myFunction() 是如何被调用的?
  • "abc".indexOf("") = 0,而不是 -1。您应该测试是否为空。
  • @RoryMcCrossan 我忘记将 HTML 输入放入代码中。我把整个代码放在我的codepen上。链接:codepen.io/Yung_n-d/pen/mdwQGqX

标签: javascript html jquery css


【解决方案1】:

'SomeString'.indexOf('') 将返回 0 而不是 -1;您还应该测试输入的值字段不为空。

更改以下行:

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

收件人:

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

【讨论】:

    猜你喜欢
    • 2013-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-21
    • 1970-01-01
    • 2013-04-19
    • 1970-01-01
    • 2015-11-29
    相关资源
    最近更新 更多