2015-10-20 117 views
1

嗨,我有以下場景。 我有工作正則表達式,但不能將它傳遞給jQuery選擇器。 我正在嘗試關注。將正則表達式傳遞給JQuery Selector

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

我的元素有ID如下 prefix_10_postfix prefix_1_postfix

請指引我。

+0

這裏請注意,在正則表達式'[\ d] {1,2}'可以用作'\ d {1,2}',沒必要的課堂和空間 – Tushar

回答

2

您可以使用的起始和屬性數值選擇結束

$('[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>

相關問題