Javascript 获取optgroup中select选项的索引

Javascript 获取optgroup中select选项的索引,javascript,Javascript,如果我有如下选项列表: <select name="optionList" id="optionList"> <optgroup label="optgroup1"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option>

如果我有如下选项列表:

<select name="optionList" id="optionList"> 
    <optgroup label="optgroup1"> 
        <option value="1">1</option> 
        <option value="2">2</option> 
        <option value="3">3</option> 
        <option value="4">4</option> 
    </optgroup> 
    <optgroup label="optgroup2"> 
        <option value="5">5</option> 
        <option value="6">6</option> 
        <option value="7">7</option> 
        <option value="8">8</option> 
    </optgroup> 
</select>

1.
2.
3.
4.
5.
6.
7.
8.
我知道我可以使用以下方式访问选定的索引:

document.getElementById('optionList')。选择索引

如果我使用上述方法,尽管选择的索引5将是4,6将是5,7将是6,等等

如何判断optgroup中的选定项在何处

总之,我希望能够查询某些内容并返回其在optgroup中的位置,这样5将返回0,6将返回1等等。

使用纯javascript

var element = document.getElementById('optionList');
console.log(element.options[element.selectedIndex].parentNode.label);

jQuery交叉浏览器解决方案:

$('#optionList option:selected').index();

这是一项稍微复杂的任务,因为没有原生的方法来完成。我将根据当前的浏览器标准来回答这个问题:在较旧的浏览器中可以做到这一点,但这需要更多的工作

var select = document.getElementById('optionList'), // the <select> element
    selectedIndex = select.selectedIndex, // 0-based index of which element in the <select> is selected
    selectedElement = select.options[selectedIndex], // DOM element selected
    optGroup = selectedElement.parentNode, // <optgroup> element
    optGroupOptions = optGroup.children, // <option> elements in the <optgroup>
    positionInOptGroup = Array.prototype.indexOf.call(optGroupOptions, selectedElement); // the selected <option>'s position in the <optgroup>
var select=document.getElementById('optionList'),//元素
selectedIndex=select.selectedIndex,//基于0的索引选择了中的哪个元素
selectedElement=select.options[selectedIndex],//选择DOM元素
optGroup=selectedElement.parentNode,//元素
optGroupOptions=optgroups.children,//中的元素
positionInOptGroup=Array.prototype.indexOf.call(optGroupOptions,selectedElement);//选定对象在列表中的位置

请注意,如果浏览器不支持(即IE请尝试以下操作),则此操作将不起作用:

function indexOf(select) {
    var options = select.options;
    var selectedOption = options.item(select.selectedIndex);
    var nodes = selectedOption.parentNode.children;

    for (var i = 0; i < nodes.length; ++i) {
        if (nodes[i] === selectedOption) {
            return i;
        }
    }

    return -1;
}

indexOf(document.getElementById('optionList'));
function indexOf(选择){
var options=select.options;
var selectedOption=options.item(select.selectedIndex);
var nodes=selectedOption.parentNode.children;
对于(变量i=0;i

工作示例:

我知道这是一个老问题,实现可能已经更改,但我在选择器更改事件中发现了简单的jQuery解决方案,例如

$(document).on('change', ".cmilestoneTaskSelector", function(e) 
  {
  alert($(this.options[this.selectedIndex]).index());
   .....
在Firefox和Chrome中测试