下拉框selectedIndex属性

时间:2013-03-12 11:19:10

标签: javascript jquery

$.fn.fillSelect = function (data) {
    return this.clearSelect().each(function () {
        if (this.tagName == 'SELECT') {
            var dropdownList = this;
            $.each(data, function (index, optionData) {
                var option = new Option(optionData.Text, optionData.Value);
                if ($.browser.msie) {
                    dropdownList.add(option);
                } else {
                    dropdownList.add(option, null);
                }
            });
            // code for access "selectedindex" 
        }
    });
};

上面是使用jQuery动态生成下拉列表的代码片段。

我需要动态设置 selectedIndex 属性值,以便更早地显示保存的值。我将把代码插入上面代码中的// code for access "selectedindex"位置。那么如何为dropdownList设置 selectedIndex 属性?

2 个答案:

答案 0 :(得分:2)

您应该能够将selectedIndex属性设置为与其他属性相同。

假设dropdownListHTMLSelectElementdropdownList.selectedIndex = 5;,应该有用。

答案 1 :(得分:1)

我会在这段代码中执行此操作:

$.each(data, function (index, optionData) {
    var option = new Option(optionData.Text, optionData.Value);
    if (/* code to determine if this is the chosen one */) {
        option.setAttribute("selected", "selected");
    }
    if ($.browser.msie) { /* etc */

您正在相关选项上设置所选属性。

相关问题