2011-04-26 52 views
7

我正在製作一個選擇菜單插件來替換醜陋的默認選擇,並且在不同操作系統中保持一致。使用jQuery在選擇菜單中添加選定的屬性

這裏的演示(僅適用於火狐和WebKit)
http://spacirdesigns.com/selectMenu/

它已經工作,但我分配「選擇」屬性選項有問題。該代碼適用於任何其他屬性,但我無法使其與所選屬性一起使用。

這工作:

select.find('option') 
    .removeAttr('whatever') 
    .eq(index).attr('whatever', 'hello'); 

這不:

select.find('option') 
    .removeAttr('selected') 
    .eq(index).attr('selected', 'selected'); 

下面是到目前爲止的代碼:

(function($){ 

     $.fn.selectMenu = function() { 

      var select = this; 
      select.hide(); 

      var title = select.attr('title'); 
      var arrow = 'img/arrow.png'; 
      var items = ''; 

      select 
       .children('option') 
       .each(function(){ 
        var item = $(this).text(); 
        if ($(this).val() != '') { 
         $(this).attr('value', item); 
        } 
        items += '<li>' + item + '</li>' 
       }); 

      var menuHtml = 
       '<ul class="selectMenu">' + 
       '<img src="' + arrow + '" alt=""/>' + 
       '<li>' + title + '</li>' + 
       '<ul>' + items + '</ul>' + 
       '</ul>'; 

      select.after(menuHtml); 

      var menu = $(this).next('ul'); 
      var list = menu.find('ul'); 

      menu 
       .hover(function(){}, function(){ 
        list.hide(); 
       }) 
       .children('li').hover(function(){ 
        list.show(); 
       }); 

      menu.find('ul li').click(function(){ 
       var index = $(this).index(); 
       menu.children('li').text($(this).text()); 
       select.find('option') 
        .removeAttr('selected') 
        .eq(index).attr('selected', 'selected'); 
       list.hide(); 
      }); 

     }; 

    })(jQuery); 
+0

您是否嘗試過使用'.attr('selected',true)'? – NT3RP 2011-04-26 13:13:39

+0

我知道這個插件支持:http://programmingdrunk.com/current-projects/dropdownReplacement/#use – mkoryak 2011-04-26 13:15:29

+0

'.attr('selected',true)'也不起作用。 – elclanrs 2011-04-26 13:17:55

回答

3

退房this previous detailled answer on SO

如果你真的想maitain HTML輸出,選擇屬性,不僅有jQuery的永葆select元素右側的selectedIndex屬性,你可以用原來的settAttr破解()函數:

select[0].options[select[0].selectedIndex].setAttribute('selected','selected'); 

但只要您繼續使用VAL jQuery方法()或「:選擇」,你should'nt得到任何問題,你可能有問題,只有當你解析HTML找到所選屬性,從來不應該做的事。

+0

Tahnk你。我發現這個其他帖子也非常有幫助http://stackoverflow.com/questions/3729741/jquery-cannot-set-selected-selected-via-attr-on-option-elements – elclanrs 2011-04-26 13:54:20

+0

是的,這是一個正確的參考。 – regilero 2011-04-26 14:00:10

0

考慮您的最新評論我想你的問題是螢火蟲,而不是你的代碼。爲什麼這與除「selected」之外的其他屬性一起工作的原因是,從下拉列表中選擇一個選項不會修改DOM中的選定屬性。我向你保證,你的代碼沒有問題。

23

從jQuery 1.6開始「爲了檢索和更改表單元素的checked,selected,or disabled等DOM屬性,請使用.prop()方法。」

$("#someselect option[value=somevalue]").prop("selected", "selected") 
+2

這應該是最好的答案,比其他老的更簡單 – 2014-08-21 01:49:41

+0

謝謝@sidarcy。這對我幫助很大。當然,它應該是最重要的。 – offshore 2015-08-18 13:26:50

+0

不應該是'.prop(「選中」,true)'?我記得,在這種情況下使用舊方法時,它必須是'.attr(「selected」,「selected」)'。 – rabudde 2016-07-19 12:32:08

相關問題