2011-09-11 255 views
4

我目前使用這個成功移除選項的jQuery選擇刪除選項

$("select#select_gender option[value='initial']").remove(); 

有沒有辦法刪除選項,而不添加到選擇 - 像下面?

$('select#select_gender').val('initial').remove(); 

THX

回答

12
$("select#select_gender option").filter("[value='initial']").remove(); 

我相信這樣做。

或根據您的最新評論:

var sel = $("select#select_gender"); 
sel.find("option[value='initial']").remove(); 

PS對不起,這麼多編輯:(

0

爲什麼你會怎麼做呢?你可以這樣做

$('select#select_gender').each(function(a,b){ 
    if ($(this).val() == 'initial'){ 
     $(this).remove(); 
    } 
}); 

我不建議這樣做。使用第一個。這是完美和容易的

+0

我在變量中使用了很好的選擇器,所以我想只引用變量名稱,例如:variable。('option')。remove();不需要重新找到選擇器...有興趣看看是否有可能...我可能會保留原樣... – Adam

1

我想你可以限制下來的選項標籤

$("select#select_genter option").find("[value='initial']").remove() 

,然後diffenet vals

var beg_string = "[value='", 
    end_string = "']", 

while () { 
    /* loop through a list of values */ 
    $("select#select_genter option").find(beg_string + val + end_str).remove(); 
} 
2

你可以使用這樣的事情:

$("#select_gender").children().filter(function(index, option) { 
    return option.value==="initial"; 
}).remove(); 

如果你願意,你可以把它變成一個插件,像這樣:

;(function($) { 
    $.fn.option=function(value) { 
     return this.children().filter(function(index, option) { 
      return option.value===value; 
     }); 
    }; 
})(jQuery); 

然後,你可以這樣做:

$("#select_gender").option("initial").remove(); 

您可以演示它here