是否有一种方法可以选择带有前缀“my”和后缀“0-9”的jQuery的所有id。 就像这些$(“#我的$ 1-4”)或只是可能与循环?jQuery选择以word为前缀并以计数器为后缀的#id
<div id="my1"/>
<div id="my2"/>
<div id="my3"/>
<div id="my4"/>
<div id="my5"/>
是否有一种方法可以选择带有前缀“my”和后缀“0-9”的jQuery的所有id。 就像这些$(“#我的$ 1-4”)或只是可能与循环?jQuery选择以word为前缀并以计数器为后缀的#id
<div id="my1"/>
<div id="my2"/>
<div id="my3"/>
<div id="my4"/>
<div id="my5"/>
的第一个想法,这似乎运作良好:
$('div[id^="my"]').filter(
function(){
return this.id.match(/\d+$/);
});
上述选择所有div
元件,其id
开始与值my
,然后过滤返回的元素到那些id
也与数字字符结束。
参考文献:
前缀部分是与attribute starts-with选择容易实现的:
$("div[id^=my]");
但没有选择,这将允许你指定一个字符范围,这样的循环将不得不参与其中。我建议filter
:
$("div").filter(function() {
return /^my\d$/.test(this.id);
});
假设你没有数以百万计的元素,与“我”,你可以做启动:
$('[id^=my]').filter(function() { return this.id.matches(/\d/) && this.id.length == 3 })
这抓起有开头的ID的所有要素“我的”,包含一些,只有3个字符长(所以“my54”不会匹配,但“my6”会)
你只需要** id **选择器?为什么不使用类,名称或数据选择器。 最后一个请参阅http://stackoverflow.com/questions/2891452/jquery-data-selector 还有像这样的属性选择器http://api.jquery.com/attribute-contains-prefix-selector/ – m03geek