jquery - 使搜索输入通过列表 Jquery 进行过滤

标签 jquery input filter hide show

嘿,我正在尝试创建一个搜索字段,该字段将根据用户输入的内容并单击搜索按钮来过滤或显示/隐藏(最好的)列表元素。我不知道该怎么做。不幸的是,我尝试的所有方法都不起作用,我不确定最好的方法,比如我使用显示和隐藏还是有更好的方法?

这是我的 HTML:

<html>
    <head>

    </head>
    <body>
    <label for="filter">Filter</label>  
    <input type="text" name="filter" value="" id="filter" />

        <a id="addtag" href="#">Search</a> 

    <ul>
        <li id="Hero1">Superman</li>
        <li id="Hero2">Batman</li>
        <li id="Hero3">Spiderman</li>
        <li id="Hero4">Iron Man</li>
        <li id="Hero5">The Hulk</li>
    </ul>

    </body>
</html>

因此,如果有人输入“Superman”并单击搜索按钮,则只会显示 Superman 列表元素。

对此的任何帮助都会很棒。谢谢。

最佳答案

这也使用 jQuery 并创建滑动动画。 这将是 HTML:

<div id="wrap">
  <h1 id="header">List of countries</h1>
  <ul id="list">
    <li><a href="#">List Item</a></li>
            <li><a href="#">Add Unlimited Items</a></li>
</ul>
</div>

JavaScript

(function ($) {
  // custom css expression for a case-insensitive contains()
  jQuery.expr[':'].Contains = function(a,i,m){
      return (a.textContent || a.innerText || "").toUpperCase().indexOf(m[3].toUpperCase())>=0;
  };


  function listFilter(header, list) { // header is any element, list is an unordered list
    // create and add the filter form to the header
    var form = $("<form>").attr({"class":"filterform","action":"#"}),
        input = $("<input>").attr({"class":"filterinput","type":"text"});
    $(form).append(input).appendTo(header);

    $(input)
      .change( function () {
        var filter = $(this).val();
        if(filter) {
          // this finds all links in a list that contain the input,
          // and hide the ones not containing the input while showing the ones that do
          $(list).find("a:not(:Contains(" + filter + "))").parent().slideUp();
          $(list).find("a:Contains(" + filter + ")").parent().slideDown();
        } else {
      $(list).find("li").slideDown();
        }
        return false;
      })
    .keyup( function () {
        // fire the above change event after every letter
        $(this).change();
    });
  }


  //ondomready
  $(function () {
    listFilter($("#header"), $("#list"));
  });
}(jQuery));

CSS 是可选的。 JSFiddle 演示:http://jsfiddle.net/4feug/

关于jquery - 使搜索输入通过列表 Jquery 进行过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1766299/

相关文章:

javascript - 滚动捕捉到页面部分

jquery - 单击 jquery + air 打开文件系统窗口

javascript - jQuery - 对表单中的每个输入值求和

collections - 如何根据 Java 8 中列表元素内的比较来过滤列表?

dataframe - 如何过滤pyspark数据框中任何列为空的行

javascript - CSS、JSP中点击按钮时一个div消失,同时出现另一个div

Java 键绑定(bind)不工作

c - 从用户获取多个整数作为输入

mysql - 在mysql中使用多列过滤数据

jquery - 带有 jquery $.ajax 的 Rails