如何使用jquery迭代多个选择选项

我只是想知道是否可以通过多个选择选项并获取它们的值和文本(如果选择了一个获取值和文本,如果选择2则获取它们的值和文本等等)

我在一个页面中有15个选择框?

任何帮助,将不胜感激。

0 1 2 3 4 5 6 7 8
0 1 2 3 4 5 6 7 8

所有选择选项都具有相同的类。

谢谢

这将提醒所有选定选项的文本和值(对于页面上的所有选项):

 $('select > option:selected').each(function() { alert($(this).text() + ' ' + $(this).val()); }); 

查看Core / each和Selectors / selected:

http://docs.jquery.com/Core/each

http://docs.jquery.com/Selectors/selected

对于optgroups …

 $("select[id^='desu']").children('optgroup').children('option:selected').each( function(id, element) { document.write(element.title); } ); 

此函数将返回与给定类匹配的选择的文本/值对数组。

 function getSelects(klass) { var selected = []; $('select.' + klass).children('option:selected').each( function() { var $this = $(this); selected.push( { text: $this.text(), value: $this.val() } ); }); return selected; } 

如果您的所有选择框都以相似的ID开头(“select_1”,“select_2”,“select_3”等),您可以执行以下操作:

 var arr = []; $("select[id^='select_']").children('option:selected').each(function(){ //you will do this once for every selected item... } 

这允许您仅循环显示特定的选择框,以防您有多个分组。

 //Another option var selected = []; $('select :has(:selected)').each( function(){ var $this = $(this); selected.push( { text: $this.text(), value: $this.val() ); }); return selected;