2010-05-06 61 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] 
}