2013-03-12 89 views
1
$.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属性

我需要动态设置selectedIndex属性值,以便更早地显示保存的值。我将在上面的代码中插入该代码到// code for access "selectedindex"的地方。那么我怎样才能为dropdownList设置selectedIndex属性?

+1

你想设置或获取selectedIndex? – 2013-03-12 11:23:22

+0

@Olylyodgson设置selectedIndex。 – Sampath 2013-03-12 11:24:08

回答

2

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

假设dropdownListHTMLSelectElement,dropdownList.selectedIndex = 5;应该工作。

+1

+1太棒了。感谢这样一个简单的解决方案。它的工作。 – Sampath 2013-03-12 11:39:33

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

你设置的相关选项选择的属性。

+0

也为你的努力+1。 – Sampath 2013-03-12 11:40:48