javascript - 使用输入过滤器在 Div 上进行实时搜索

标签 javascript jquery html css

https://jsfiddle.net/Lh9efLxm/

我在使用实时搜索脚本时遇到了一些问题。

我有一些 div 作为“行”,一些 p 作为“列”声明

作为#filter 的输入字段应该隐藏所有不相关的“行”(div)

$('#results div').hide();

但我似乎有些想念。

有人能帮帮我吗? 谢谢

最佳答案

在您的脚本中,您隐藏和显示所有 #results div 而不是 each 循环中的特定一个。因此,将选择器更改为 this

另外,您忘记在 fiddle 中包含 jQuery。

    $("#filter").keyup(function() {

      // Retrieve the input field text and reset the count to zero
      var filter = $(this).val(),
        count = 0;

      // Loop through the comment list
      $('#results div').each(function() {


        // If the list item does not contain the text phrase fade it out
        if ($(this).text().search(new RegExp(filter, "i")) < 0) {
          $(this).hide();  // MY CHANGE

          // Show the list item if the phrase matches and increase the count by 1
        } else {
          $(this).show(); // MY CHANGE
          count++;
        }

      });

    });
.header {
  display: flex;
}

.header p {
  flex: 1;
  font-weight: bold;
}

.results {
  display: flex;
}

.results p {
  flex: 1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="filter" type="text">

<div id="header">
  <div class="header">
    <p>ID</p>
    <p>Manufacturer</p>
    <p>Type</p>
    <p>PS</p>
  </div>
</div>

<div id="results">
  <div class="results">
    <p>1</p>
    <p>Toyota</p>
    <p>C 200</p>
    <p>114</p>
  </div>
  <div class="results">
    <p>2</p>
    <p>Mercedes</p>
    <p>C 220</p>
    <p>144</p>
  </div>
</div>

JSFiddle

关于javascript - 使用输入过滤器在 Div 上进行实时搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44736054/

相关文章:

javascript - 即使有 When Promise 回调金字塔

javascript - sankey.js 中基于 JSON 的节点着色

javascript - Uint8ClampedArray 替代或使 Uint8Array 产生字节值的钳制字符串

jquery - WordPress+SmoothDivScroll+Colorbox : Include a permalink for each of the respective image in colorbox

javascript - 检测/拦截 <img> 插入 DOM

javascript - 元素漂浮在 Bootstrap 模式之外

html - z-index 值未按应有的方式工作 - z-index 50 元素显示在下方

javascript - 为什么点击或更改事件都没有触发我的功能?

javascript - 在 contenteditable div 中使用焦点元素?

html - 仅将 CSS 水平下拉菜单中的顶部索引菜单项居中