2013-04-30 40 views
0

我已經把這裏演示:http://jsfiddle.net/JjBPd/的jQuery的onchange輸球選中狀態

$(function() { 
    var options = $("select#areafilter").children("option"); 
    var selectoption = $("select#regionfilter"); 
    $(selectoption).on("change", function() { 
     var selected = $(this).children("option:selected").data("path"); 
     $(options).appendTo("select#areafilter"); 
     $(options).each(function() { 
      var region = $(this).data("region"); 
      if (region != selected && region != 'default') { 
       $(this).remove(); 
      } 
     }); 
     if (selected == 'default') { 
      $(options).appendTo("select#areafilter"); 
     } 
    }); 
}); 

基本上,如果你選擇一個區域,然後選擇和區域,然後按區域再次選擇過濾器,它加載與的最後一個選項突出顯示選擇列表,我嘗試使用selected ='selected'並重點關注,但沒有喜悅。

回答

0

如果你想在區域選擇框每個區域改變時重新設置,你可以使用jQuery的prop()方法:

$(selectoption).on("change", function() { 
    // reset the selected area 
    options.prop('selected',false); 

    ... 

看到一個forked and updated fiddle here

編輯: 這裏的更新在Firefox中工作,以及代碼。結果表明Firefox在追加時會創建新的元素,而Webkit只是引用現有的元素。因此你必須重新設置新添加的選項。小提琴應該更新。

$(function() { 
    var options = $("select#areafilter").children("option"); 
    var selectoption = $("select#regionfilter"); 
    $(selectoption).on("change", function() { 

     var selected = $(this).children("option:selected").data("path"); 
     $(options).appendTo("select#areafilter"); 
     $(options).each(function() { 
      var region = $(this).data("region"); 
      if (region != selected && region != 'default'){ 
       $(this).remove(); 
      } 
     }); 
     if (selected == 'default') { 
      $(options).appendTo("select#areafilter"); 
     } 

     // reset the selected area 
     $("select#areafilter").children().prop('selected',false).first().prop('selected',true); 
    }); 
}); 
+0

感謝您抽出寶貴的時間,在Firefox :( – user989952 2013-04-30 02:50:19

+0

你是正確的回答,遺憾的是仍然不工作!它確實* *在Chrome/Safari瀏覽器的工作,但是這很有趣... – 2013-04-30 02:56:03

+0

真棒非常感謝你的幫助 :) – user989952 2013-04-30 03:15:29