gpt4 book ai didi

jquery - 将正则表达式传递给 JQuery 选择器

转载 作者:行者123 更新时间:2023-12-01 07:48:19 26 4
gpt4 key购买 nike

嗨,我有以下场景。我有工作正则表达式,但无法将其传递给 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可以与属性选择器结合使用。

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>

关于jquery - 将正则表达式传递给 JQuery 选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33238616/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com