我正在尝试在keypress
上启动图像库的搜索(或更确切地说是过滤)。用户开始输入图像名称,任何与搜索词不匹配的图像名称都会被隐藏:
<div id="abc" data-imgName="abc"></div>
<div id="abc2" data-imgName="abc2"></div>
<div id="xyz" data-imgName="xyz"></div>
因此,如果用户开始输入“ab”,则:$('#xyz').hide();
我该怎么做?我可以在属性上使用正则表达式吗?
最佳答案
//bind an event handler to the text input for the keyup event (so the value will have changed by the time this event fires)
$('input[type="text"]').on('keyup', function (event) {
//convert the value of the text box to lowercase
this.value = this.value.toLowerCase();
//cache the elements that match the search
var good_to_go = $('[data-imgName*=' + $(this).val() + ']').show();
//hide all the elements that do not match the search
$('[data-imgName]').not(good_to_go).hide();
});
可能有一种方法可以实现更好的效果,但这需要文本输入的值并查找具有包含文本输入值的 data-imgName
属性的所有元素。然后,它会查找所有具有 data-imgName
属性的元素,并隐藏所有尚未找到的元素。
如果所有搜索元素都有一个父元素,则应该用它来启动所有选择器以避免搜索整个 DOM:
var $container = $('#container-id');
$('input[type="text"]').on('keyup', function (event) {
this.value = this.value.toLowerCase();
if (this.value == '') {
$container.children().show();
} else {
var good_to_go = $container.find('[data-imgName*="' + this.value + '"]').show();
$container.find('[data-imgName]').not(good_to_go).hide();
}
});
请注意,此示例还检查文本框的值是否为空,如果是,则显示所有搜索到的元素。
以下是 *=
(包含)选择器的文档:http://api.jquery.com/attribute-contains-selector/
以下是 .not()
函数的文档:http://api.jquery.com/not
这是一个工作演示:http://jsfiddle.net/HRjHV/3/
关于javascript - 使用 Regex/jQuery 匹配 HTML 属性(用于搜索),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8858688/