Jquery – 在select中选择optgroup

我有2个选择组的选择。 有没有办法只在选择第一个optgroup中的选项时调用函数,如果选择了第二个optgroup的选项,则调用另一个函数?

当然。

HTML:

What is your preferred vacation spot?

JS:

 $("#my_select").change(function(){ var selected = $("option:selected", this); if(selected.parent()[0].id == "one"){ //OptGroup 1, do something here.. } else if(selected.parent()[0].id == "two"){ //OptGroup 2, do something here } }); 

示例: http : //jsfiddle.net/pyG2v/

 $('#selectID').change(function(){ var $option = $('option:selected', this); // get selected option var optGroup = $option.closest('optgroup').index(); // get which optgroup if(optGroup == 0){ // first } else if(optGroup == 1){ // second } else{ // not first or second } }); 

单击选项时,您将获得选项组的Id名称。

  var obj = {}; $('select[name=queue]').on('change', function () { obj = {}; var options = $('option:selected', this); //the selected options $.each(options, function (index, option) { var optgroupIndex = $(option).closest('optgroup').index() //get the index var optgroupId = $(option).parent()[0].id //get id if (obj.hasOwnProperty(optgroupId)) { obj[optgroupId].push($(option).val()); } else { obj[optgroupId] = [$(option).val()]; } }); var textRows = []; $.each(obj, function(optgroupId, values){ textRows.push(optgroupId +": " + values.join(', ')); }); $('#demo').html(textRows.join("
")); });
  /*Additional*/ select::-webkit-scrollbar {display:none;} select::-moz-scrollbar {display:none;} select::-o-scrollbar {display:none;} select::-google-ms-scrollbar {display:none;} select::-khtml-scrollbar {display:none;} select{height:150px;}