2013-09-30 136 views
7

什麼是最簡單的方式來遍歷所有選擇下拉ID與ID匹配模式使用jQuery。例如:Jquery選擇器以獲得所有選擇下拉ID模式

<select id="begin_1_end">...</select> 

<select id="begin_32_end">...</select> 

<select id="begin_42_end">...</select> 

<select id="dontgetme_2_end">...</select> 

<select id="begin_12_dontgetme">...</select> 

只能遍歷前3個選擇。

+0

類似:HTTP:// stackove rflow.com/questions/1487792/jquery-find-element-whose-id-has-a-particular-pattern/1487882 – cdmckay

回答

22

attribute-starts-with-selector/

$('select[id^="begin"]').each(function() { 
    console.log(this.id); 
}); 

試試這個,或者你可以使用attribute-ends-with-selector

$('select[id$="end"]').each(function() { 
    console.log(this.id); 
}); 

更新

選擇的第一個3你可以使用:lt(3)這樣

$('select[id^="begin"]:lt(3)').each(function() { 
    console.log(this.id); 
}); 

DEMO

更新

要合併的選擇,你可以做到這一點

$('select[id^="begin"][id$="end"]').each(function() { 
    console.log(this.id); 
}); 

DEMO

如果您想選擇與開頭編號的元素開始OR結束時,您可以使用,得到兩種不同的選擇

做到這一點
$('select[id^="begin"],select[id$="end"]').each(function() { 
    //    ^
    console.log(this.id); 
}); 

DEMO

+0

謝謝。你如何結合開始和結束模式?請參閱最新的問題。日Thnx。有時起始模式匹配而不是結束。 –

+0

在您更新的問題中,您只想選擇前三個,然後我的答案中的最近更新之一應該可以工作。你測試過了嗎? @RayS。 – Anton