【问题标题】:jQuery filter with imputs (include / inside checkbox)带有输入的 jQuery 过滤器(包括/内部复选框)
【发布时间】:2021-07-09 18:32:13
【问题描述】:

我想问是否有人知道如何解决我的问题。过滤适用于其他所有(我想不区分大小写),但在搜索“食物”后不会出现复选框。我需要创建一个带有复选框的类别列表。如果您搜索一个类别,您可以立即选中复选框

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("#myInput").on("keyup", function() {
    var value = $(this).val().toLowerCase();
    $("#myDIV *").filter(function() {
      $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
    });
  });
});
</script>
</head>
<body>

<h2>Filter</h2>
<!--Type something in the input field to search for a specific text inside the div element with id="myDIV" -->
<input id="myInput" type="text" placeholder="Search..">

<div id="myDIV">
  <p>dog</p>
  <div>master20</div>
  <button>Button</button>
  <p>Welcome5</p>
  <label class="important_class_for_me">Food
    <input type="checkbox">
    <span class="my_custom_checkmark"></span>
  </label>
</div>
  
</body>
</html>

【问题讨论】:

  • 那种非常松散的结构不太利于你想做的事情。

标签: javascript html jquery checkbox filter


【解决方案1】:

问题是字符*,选择器$("#myDIV *")。通过指定此字符,您将所有子代都称为parent - child - child - child ...

您只需要引用父 #myDIV 的第一个孩子。将* 替换为&gt;。像这样:

$("#myDIV >").filter(function() { ... }

$(document).ready(function () {
    $("#myInput").on("keyup", function () {
        var value = $(this).val().toLowerCase();
        $("#myDIV >").filter(function () {
            $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1);
        });
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<h2>Filter</h2>
<!--Type something in the input field to search for a specific text inside the div element with id="myDIV" -->
<input id="myInput" type="text" placeholder="Search.." />

<div id="myDIV">
    <p>dog</p>
    <div>master20</div>
    <button>Button</button>
    <p>Welcome5</p>
    <label class="important_class_for_me">
        Food
        <input type="checkbox" />
        <span class="my_custom_checkmark"></span>
    </label>
</div>

【讨论】:

    【解决方案2】:

    你隐藏了 myDIV 中的每一个元素,不仅是吓人的孩子。

    碰巧:

    <input type="checkbox">
    <span class="my_custom_checkmark"></span>
    

    两者都是孩子,并且没有 .text(),因此它们会切换。

    相反,只需通过将$("#myDIV *") 更改为$("#myDIV &gt; *") 来对恐吓孩子进行过滤

    【讨论】:

      猜你喜欢
      • 2017-12-07
      • 2020-08-16
      • 1970-01-01
      • 2011-03-27
      • 2023-04-05
      • 2011-02-21
      • 2011-10-25
      • 1970-01-01
      • 2019-03-22
      相关资源
      最近更新 更多