嗨,我有以下场景。 我有工作正则表达式,但无法将其传递给 jQuery 选择器。 我正在尝试关注。
$("#prefix_[\d]{1, 2}_postfix")
我的元素的 ID 如下 前缀_10_后缀 prefix_1_postfix
请指导我。
最佳答案
您可以使用属性值选择器开头和结尾
$('[id^="prefix_"][id$="_postfix"]')
这将选择 id 以 prefix_ 开头并以 _postfix 结尾的所有元素。
如果页面包含很多id以prefix_
开头的元素并以 _postfix
结尾但不符合它们之间应该是一个或两个数字的标准,例如。 <div id="prefix_tushar_postfix"></div>
,开头为和结尾为选择器将不起作用。在这种情况下filter
可以与属性选择器结合使用。
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>
关于jquery - 将正则表达式传递给 JQuery 选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33238616/