这个JQuery代码如何用于从表中过滤数据?

时间:2014-01-23 09:26:56

标签: jquery

有人可以向我解释下面的代码是做什么的吗?

<script>
 $(document).ready(function() {
     $('input.filter').on('keyup', function() {
          var rex = new RegExp($(this).val(), 'i');
          $('.searchable tr').hide();
          $('.searchable tr').filter(function() {
               return rex.test($(this).text());
          }).show();
      });
 });
</script>

根据输入的值过滤表中的数据。

我可以理解基本功能,但我错过了整体思维概念。

有人可以解释一下吗?

1 个答案:

答案 0 :(得分:1)

每次输入内容(keyup事件)时,隐藏所有<tr>,然后查找包含您键入的文本的所有<tr>,然后显示它们。

<script> 
    $(document).ready(function() {

     // key up from an input with class filter
     $('input.filter').on('keyup', function() {

          // create regular expression from value of the input
          var rex = new RegExp($(this).val(), 'i');

          // hide all <tr>
          $('.searchable tr').hide();

          // show all <tr> which contains your text
          $('.searchable tr').filter(function() {
               return rex.test($(this).text());
          }).show();
      }); 
}); 
</script>

正则表达式部分:

  

var rex = new RegExp($(this).val(),&#39; i&#39;);

这将创建一个与您在输入中输入的值匹配的正则表达式。 i参数表示不区分大小写。

filter()中,您正在测试return rex.test($(this).text());。在这里,您使用自定义过滤功能。只有包含您文本的行不会被过滤掉(然后会显示这些行)。

例如:

var rex = new RegExp('hello', 'i'); //you typed "hello" in the input
rex.test('hello world'); // true - contains hello
rex.test('HEllo world'); // true - contains hello (case insensitive)
rex.test('lorem ipsum'); // false - no hello present

jQuery过滤器()

如果您有以下HTML:

<a href="http://www.google.com">Link 1</a>
<a href="http://google.com" rel="nofollow">Link 2</a>
<a href="https://www.google.com">Link 3</a>
<a href="http://bing.com" class="red">Link 4</a>
<a href="http://www.bing.com" class="red">Link 5</a>
<a href="http://localgoogle.com">Link 6</a>

并且您运行$('a').hide().filter('.red').show();,只会显示Link 4Link 5。它与您的概念相同,但改为使用自定义过滤器。