【问题标题】:Pass Regex To JQuery Selector将正则表达式传递给 JQuery 选择器
【发布时间】:2016-01-19 05:29:09
【问题描述】:

您好,我有以下情况。 我有工作正则表达式,但不能将它传递给 jQuery 选择器。 我正在尝试关注。

$("#prefix_[\d]{1, 2}_postfix")

我的元素的 id 如下 prefix_10_postfix prefix_1_postfix

请指导我。

【问题讨论】:

  • 这里注意,在正则表达式中[\d]{1, 2}可以用作\d{1,2},不需要class和空格

标签: jquery regex jquery-selectors


【解决方案1】:

您可以使用以属性值选择器开头和结尾

$('[id^="prefix_"][id$="_postfix"]')

这将选择id以prefix_开头并以_postfix结尾的所有元素。


如果页面包含许多 id 以prefix_ 开头并以_postfix 结尾的元素,但与它们之间应该是一两个数字的条件不匹配,例如。 <div id="prefix_tushar_postfix"></div>,以选择器开头和以选择器结尾将不起作用。在这种情况下,filter 可以与属性选择器结合使用。

Demo

var regex = /^prefix_\d{1,2}_postfix$/;

// Narrow down elements by using attribute starts with and ends with selector
$('[id^="prefix_"][id$="_postfix"]').filter(function() {
  
  // filter the elements that passes the regex pattern
  return regex.test($(this).attr('id'));
}).css('color', 'green');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="prefix_1_postfix">prefix_1_postfix</div>
<div id="prefix_123_postfix">prefix_123_postfix</div>
<div id="prefix_tushar_postfix">prefix_tushar_postfix</div>
<div id="prefix__postfix">prefix__postfix</div>
<div id="prefix_11_postfix">prefix_11_postfix</div>
<div id="prefix_aa_postfix">prefix_aa_postfix</div>

【讨论】:

    猜你喜欢
    • 2010-09-16
    • 1970-01-01
    • 1970-01-01
    • 2012-06-12
    • 2012-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多