2009-09-24 103 views

回答

4

我建議使用jQuery(或其他框架),以快速處理DOM選擇。給每個optgroup一個類,以便更容易抓取它。

$("optgroup.className").children().attr('selected','selected'); 

如果您想選擇基於用戶選擇的組整組,請執行下列操作:

$("optgroup.className").select(function(e) { 
    $(this).children().attr('selected','selected'); 
}); 

**兩個例子是未經測試的僞代碼,但它們應該以最小的努力必要時進行更改。

如果你不能使用框架,你必須自己遍歷DOM才能找到optgroup和children。您可以將偵聽器附加到select元素上以獲取所選元素,然後也可以通過這種方式遍歷子元素。

+2

嗯,我試圖找到沒有jQuery的解決方案。但看着簡單的方法來做到這一點;和另一邊:遍歷DOM .... Jquery它。 – blub 2009-09-24 20:46:06

+2

@blub - 我想很多人都以這種方式進入jQuery。 ;-) – 2009-09-24 20:48:32

+0

自己遍歷DOM並不是非常困難,但框架只是讓它更容易。 'document.getElementById('selectElementID')'會給你選擇元素本身。然後,它只是遍歷其子元素的問題,或者您可以添加事件偵聽器來捕獲select事件,並解析它是否是您想要的optgroup。如果是這樣,那麼你會遍歷optgroup兒童並選擇它們。 – 2009-09-24 20:52:00

2

的jQuery:

$('#myoptgroup option').attr('selected', true); 
4

我通常反對像這樣簡單的工作使用jQuery,但我可以在這裏看到它的價值。不過,如果你喜歡一個非jQuery的解決方案,將不使用庫,引入無雜散ID或類和運行速度更快的優勢,這裏是一個:

<script type="text/javascript"> 

function selectOptGroupOptions(optGroup, selected) { 
    var options = optGroup.getElementsByTagName("option"); 
    for (var i = 0, len = options.length; i < len; i++) { 
     options[i].selected = selected; 
    } 
} 

function selectOptGroup(selectId, label, selected) { 
    var selectElement = document.getElementById(selectId); 
    var optGroups = selectElement.getElementsByTagName("optgroup"); 
    var i, len, optGroup; 
    for (i = 0, len = optGroups.length; i < len; i++) { 
     optGroup = optGroups[i]; 
     if (optGroup.label === label) { 
      selectOptGroupOptions(optGroup, selected); 
      return; 
     } 
    } 
} 

</select> 

<select id="veg" multiple> 
    <optgroup label="roots"> 
     <option>Swede</option> 
     <option>Carrot</option> 
     <option>Turnip</option> 
    </optgroup> 
    <optgroup label="leaves"> 
     <option>Spinach</option> 
     <option>Kale</option> 
    </optgroup> 
</select> 

<input type="button" onclick="selectOptGroup('veg', 'roots', true)" value="Select roots"> 

如果您<optgroup>有一個id你可以這樣做使用selectOptGroup函數,直接將optgroup傳遞給selectOptGroupOptions

2

我剛纔嘗試做類似的事情。

我想單擊組標籤時選擇<optgroup><option> s。第一次嘗試是這樣的:

$('select > optgroup').click(function() { 
    $(this).children().attr('selected', true); 
}); 

該解決方案一半的工作...

在點擊<optgroup>的標籤所有的孩子成了選擇。

但是當只需點擊一個<option>它仍然選擇組中的所有其他<option>!問題在於事件冒泡,因爲<option>在技術上也在<optgroup>之內。

因此,拼圖的最後一部分是在實際點擊<option>的情況下壓制事件向上冒泡。最終的解決方案,然後成爲:

$('select > optgroup').click(function() { 
    $(this).children().attr('selected', true); 
}); 

$('select > optgroup > option').click(function (e) { 
    if (!e) var e = window.event; 
    e.cancelBubble = true; 
    if (e.stopPropagation) e.stopPropagation(); 
}); 

工作完成!

編輯

僵硬,這並不在IE8中工作的工作(和可疑< IE8 - 也許IE9)...

它決定完全忽略兩者和元素上的點擊事件。我能想到的唯一替代方案是將元素放置在optgroup標籤上方以捕獲點擊,但其可能不值得這種努力...