【问题标题】:jQuery selector :contains - Use regular expressionsjQuery 选择器 :contains - 使用正则表达式
【发布时间】:2012-03-07 18:16:39
【问题描述】:

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

$(list).find("a:contains(" + filter + ")").parent().show();

这显示了所有包含“过滤”文本的元素。我只想显示单词以“过滤”文本开头的那些元素。

我正在考虑为此使用正则表达式。

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

【问题讨论】:

    标签: jquery regex jquery-selectors


    【解决方案1】:

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

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

    【讨论】:

    • +1 第一个并使用this.textContent || this.innerText :)
    • 很棒的解决方案! :D 如果您需要正则表达式,只需将 return 语句更改为 return (this.textContent || this.innerText).match(some_regex);
    • 加上取消......你的解决了这个问题的“使用正则表达式要求”
    猜你喜欢
    • 1970-01-01
    • 2010-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-12
    • 2012-05-14
    • 1970-01-01
    相关资源
    最近更新 更多