2013-11-14 495 views
4

如果我有一个选项列表,如下面:获取选择选项的指数OPTGROUP

<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> 

我知道我可以使用访问的selectedIndex:

document.getElementById('optionList').selectedIndex;

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

如何判断optgroup中的选定项目在哪里?

总之我希望能够查询的东西,回到它的位置在OPTGROUP使5将返回0,6将返回1等等

回答

5

这是一个稍微复杂的任务,因为没有原生的方式来完成它。我将根据当前的浏览器标准来回答:可以在较旧的浏览器中执行此操作,但这是更多的工作。

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> 

(jsFiddle)

注意的是,如果浏览器不支持Element#children这是不行的(即IE < 9)。您将不得不将childNodes集合过滤到数组中。同样的,它需要Array#indexOf,也没有在IE <存在9.

1

与纯JavaScript

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

jQuery的跨浏览溶液:

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

preview

0

试试这个:

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')); 

工作样本:http://jsfiddle.net/49R7k/1/