2010-05-06 63 views
1

假设你有一些<div> S:jQuery的通配符选择

<div id="div_num1"></div> 
<div id="div_num2"></div> 
<div id="div_num3"></div> 

您可以通过选择$("div[id^='div_num']")选择所有这些div。你怎么能buld一个函数引用后缀的前缀号码?

例如,将提醒号码3为"div_num3"的功能。

更一般地说,如何在jQuery选择器中使用全面的正则表达式?

回答

5

如果你有一组元素,你可以遍历,并得到数有:

$("div[id^='div_num']").each(function() { 
    if (this.id.match(/^div_num(\d+)$/)) { 
     alert(RegExp.$1); 
    } 
}) 
+0

谢谢,有没有优雅的方式做这个? – 2010-05-06 09:08:26

+0

@Yuval A:那*是优雅的方式。你不能在jQuery选择器中使用正则表达式。 – 2010-05-06 09:10:35

+0

@Yuval答:如果你的意思是优雅的方式就像选择器不只是用来描述元素属性来选择它们(这是选择器的用途)。那就不要。 – Gumbo 2010-05-06 09:10:56

1

应该是这样的:

$('div[id^=div_num]').click(function() { 
    var m = /div_num(\d+)/.exec($(this).attr('id')); 
    if (m == null) // no match 
     return; 
    alert(m[1]); // note that the match will be in m[1], not m[0] 
}