2013-03-12 111 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

相關問題