AMB*_*sra 2 regex jquery jquery-selectors
嗨,我有以下场景。我有工作正则表达式,但不能将它传递给 jQuery 选择器。我正在尝试跟随。
?$("#prefix_[\d]{1, 2}_postfix")
我的元素的 ID 如下 prefix_10_postfix prefix_1_postfix
请指导我。
您可以使用以属性值选择器开头和结尾
$('[id^="prefix_"][id$="_postfix"]')
Run Code Online (Sandbox Code Playgroud)
这将选择所有 id 以prefix_ 开头并以_postfix结尾的元素。
如果页面包含许多元素,其 id 以 id 开头prefix_和结尾,_postfix但不符合在它们之间应该是一两个数字的条件,例如。<div id="prefix_tushar_postfix"></div>,以选择器开头和结尾的选择器将不起作用。在这种情况下filter可以与属性选择器结合使用。
$('[id^="prefix_"][id$="_postfix"]')
Run Code Online (Sandbox Code Playgroud)
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');Run Code Online (Sandbox Code Playgroud)