如何使用正则表达式使用jQuery通过ID选择元素? [英] How can I select an element by ID with jQuery using regex?
问题描述
我有以下输入元素:
<input id="AAA_RandomString_BBB" type="text" />
<input id="AAA_RandomString_BBB_Start" type="text" />
<input id="AAA_RandomString_BBB_End" type="text" />
AAA& BBB是常数,我将永远知道它们是什么。但是RandomString总是随机的。
AAA & BBB are constants and I will always know what they are. However RandomString will always be random.
我想得到AAA_RandomString_BBB的值。我不希望输入元素的值以_Start或_End结尾。
I want to get the value of AAA_RandomString_BBB. I do not want the values from the input elements with ID ending in either _Start or _End.
我尝试了以下内容:
$('[id^="AAA_"]')
但是上面选择了所有ID为AAA _的输入元素
But the above selects all of the input elements that have an ID starting with "AAA_"
我需要一些方法来选择使用正则表达式类型的语法:
I need some way to select using a regex type syntax like:
$('[id^="AAA_(.+?)_BBB"]')
这可能吗?如果没有,任何人都可以建议选择方法
Is this possible? If not, can anyone suggest a method of selecting
推荐答案
你可以在多个属性选择器。
$("[id^=AAA_][id$=_BBB]")
It将返回与所有指定属性过滤器匹配的所有元素:
It will return all the elements that matches all the specified attribute filters:
-
[id ^ = AAA _]
匹配id的元素
属性以AAA _
开头, -
[id $ = _ BBB]
匹配id的元素
以_BBB
结尾的属性。
[id^=AAA_]
matches elements withid
attribute starting withAAA_
, and[id$=_BBB]
matches elements withid
attribute ending with_BBB
.
另一种通用替代方案:
- 使用自定义
:regex()
选择器, - 使用
.filter()
-基于方法。
- Using a custom
:regex()
selector, - Using a
.filter()
-based approach.
这篇关于如何使用正则表达式使用jQuery通过ID选择元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!