2010-06-12 64 views
5

好的,Opera瀏覽器的JS代碼似乎存在問題,因爲它只刪除在多選標記中選擇的最後一個選項標記,有人可以幫助我。多個選擇刪除多個選項的問題

下面是這個HTML:

<select id="actions_list" name="layouts" multiple style="height: 128px; width: 300px;"> 
    <option value="forum">forum</option> 
    <option value="collapse">collapse</option> 
    <option value="[topic]">[topic]</option> 
    <option value="[board]">[board]</option> 
</select> 

Ofcourse這是一個表單標籤內,但有參與這種形式的一噸多的代碼,但在這裏是此相關的信息。

這是JS應該處理這個,但只刪除Opera中的最後一個選擇的選項,不確定其他瀏覽器,但它確實需要刪除所有選擇的選項,而不僅僅是最後選擇的選項... argg

var action_list = document.getElementById("actions_list"); 
var i = action_list.options.length; 
while(i--) 
{ 
    if (action_list.options[i].selected) 
    { 
     action_list.remove(i); 
    } 
} 

這是什麼問題?我無法弄清楚一位:(

謝謝:)

回答

8

這是最簡單的使用jQuery做到這一點,但它要你可以用簡單的Javascript來做到這一點。

您遇到的問題是,當您從Opera的選項列表中刪除一個項目時,它將取消選擇所有選定的項目,因此只有第一個被刪除。解決方法是首先記住在刪除任何項目之前選擇了哪些項目。

var action_list = document.getElementById("actions_list"); 

// Remember selected items. 
var is_selected = []; 
for (var i = 0; i < action_list.options.length; ++i) 
{ 
    is_selected[i] = action_list.options[i].selected; 
} 

// Remove selected items. 
i = action_list.options.length; 
while (i--) 
{ 
    if (is_selected[i]) 
    { 
     action_list.remove(i); 
    } 
} 
+0

感謝百萬,從來沒有想過這樣做。這真是讓我失望了。他們爲什麼不能同樣工作...... argg ......那是多元化的榮耀。歡呼聲:)順便說一句,我對jQuery不是很熟悉,就像它所說的那樣容易,但我想我只是一個老式的傻瓜,更喜歡JS。再次感謝! :) – SoLoGHoST 2010-06-12 06:17:08

5

你可以做到這一點很容易使用jQuery

$('#actions_list option:selected').remove() 
+0

我需要包括這個工作庫?如果是這樣,我需要哪一個? – SoLoGHoST 2010-06-12 04:57:20

+0

您發佈的代碼不起作用... arggg – SoLoGHoST 2010-06-12 05:00:06

+0

@SoLoGHoST - 如果您只是下載並使用jQuery,它工作正常。 – 2010-06-12 05:15:34

0
$.each($('[name="alltags"] option:selected'), function(index, value) { 
    $(this).remove(); 
}); 

試試這個,而不是刪除多個選擇

0

去除選擇多個選項基於條件:

while(SelectBox.length > 1){ 
    if(SelectBox[SelectBox.length -1].text != "YourCondition"){ 
     SelectBox.remove(SelectBox.length -1); 
    } 
}