使用jquery获取optgroup中select选项的索引

使用jquery获取optgroup中select选项的索引

本文介绍了使用jquery获取optgroup中select选项的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下选择:

<select name="end" id="end">
    <optgroup label="Morning">
        <option value="12:00a">12:00 am</option>
        <option value="12:30a">12:30 am</option>
        <option value="1:00a">1:00 am</option>
        <option value="1:30a">1:30 am</option>
    </optgroup>
    <optgroup label="Evening">
        <option value="12:00p">12:00 pm</option>
        <option value="12:30p">12:30 pm</option>
        <option value="1:00p" selected="selected">1:00 pm</option>
        <option value="1:30p">1:30 pm</option>
    </optgroup>
</select>

我需要找到所选选项的整体索引,但是optgroup使这很困难。换句话说,所选择的应返回6,但它返回2.我试过这个:

I need to find the overall index of the selected option, but the optgroup is making that difficult. In other words, the selected one should return 6, but it is returning 2. I tried this:

var idx = $('#end :selected').prevAll().size();

但是返回该optgroup中的索引,而不是整个索引。我无法更改选择选项的格式或值。

But that returns the index within that optgroup, not the overall index. I can't change the format or values of the select options.

推荐答案

嗯...为什么不好的旧DOM方法?对于单选:

Erm... whyever not good old DOM methods? For a single-select:

var idx= document.getElementById('end').selectedIndex;

// or $('#end')[0].selectedIndex if you must

或者,也适用于多选,获取您感兴趣的选项元素节点并获取就可以了。

Or, which will also work on multi-selects, get the option element node you're interested in and fetch option.index on it.

这比使jQuery处理复杂选择器要快得多,也简单得多。

This is massively faster and simpler than getting jQuery to process complex selectors.

这篇关于使用jquery获取optgroup中select选项的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 19:11