jQuery selector:contains - 使用正则表达式

Nil*_*esh 14 regex jquery jquery-selectors

我正在尝试使用jQuery实现列表的搜索功能.我使用以下行来过滤匹配元素

$(list).find("a:contains(" + filter + ")").parent().show();
Run Code Online (Sandbox Code Playgroud)

这显示了包含"过滤器"文本的所有元素.我想只显示那些单词以"filter"文本开头的元素.

我正在考虑使用正则表达式.

有没有办法将正则表达式传递给:contains选择器?或者这可以通过任何其他方式实现吗?

And*_*y E 17

你需要使用.filter(),但好消息是你不需要正则表达式:

$(list).find("a").filter(function () {
    return (this.textContent || this.innerText || '').indexOf(filter) === 0;
}).parent().show();
Run Code Online (Sandbox Code Playgroud)

  • 很棒的解决方案!:D如果你需要正则表达式,只需将return语句改为`return(this.textContent || this.innerText).match(some_regex);` (6认同)