有人能向我解释一下下面的代码是干什么的吗?
<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>它根据输入的值过滤表中的数据。
我能理解基本的功能,但我错过了整体思维的概念。
谁能解释一下吗?
发布于 2014-01-23 09:29:12
每次键入某些内容(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 =新的RegExp($(this).val(),'i');
这将创建一个正则表达式,它将与您在输入中输入的值匹配。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 presentjQuery filter()
如果您有以下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 4和Link 5。对于您来说,这是相同的概念,但是使用了自定义过滤器。
https://stackoverflow.com/questions/21304107
复制相似问题