使用Regex/jQuery匹配HTML属性(用于搜索)

Kyl*_*yle 0 javascript regex jquery

我正在尝试keypress为图像库启动搜索(或者更确切地说是过滤).用户开始键入图像的名称,并且隐藏与搜索词不匹配的任何图像名称:

<div id="abc" data-imgName="abc"></div>
<div id="abc2" data-imgName="abc2"></div>
<div id="xyz" data-imgName="xyz"></div>
Run Code Online (Sandbox Code Playgroud)

因此,如果用户开始输入"ab",则: $('#xyz').hide();

我怎样才能做到这一点?我可以在属性上使用正则表达式吗?

Jas*_*per 5

//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();
});
Run Code Online (Sandbox Code Playgroud)

可能有一种方法可以做得更好,但这会获取文本输入的值,并查找具有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();
    }
});
Run Code Online (Sandbox Code Playgroud)

请注意,此示例还检查文本框的值是否为空,如果是,则显示所有搜索的元素.

以下是*=(包含)选择器的文档:http://api.jquery.com/attribute-contains-selector/

以下是该.not()函数的文档:http://api.jquery.com/not

这是一个工作演示:http://jsfiddle.net/HRjHV/3/

  • 我也会把它变成`var good_to_go = $('[data-imgName*='+ $(this).val()+']').show()`.这样,如果用户退格并且查询现在与该项匹配,则将再次显示隐藏项. (2认同)