jquery 选择删除选项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7375491/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 23:45:07  来源:igfitidea点击:

jquery select remove option

jquery

提问by Adam

I'm currently using this successfully to remove an option

我目前正在成功地使用它来删除一个选项

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

Is there a way remove an option without adding to the selector - like below?

有没有办法在不添加到选择器的情况下删除选项 - 如下所示?

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

thx

谢谢

回答by Joseph Marikle

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

I believe that does it.

我相信这样做。

or per your latest comment:

或根据您的最新评论:

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

PS sorry for so many edits :(

PS抱歉有这么多编辑:(

回答by icktoofay

You could use something like this:

你可以使用这样的东西:

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

If you wanted, you could turn it into a plugin, like so:

如果你愿意,你可以把它变成一个插件,像这样:

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

Then you could use this:

然后你可以使用这个:

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

You can demo it here.

你可以在这里演示。

回答by NebulaFox

I suppose you can restrict it down to the option tags

我想您可以将其限制为选项标签

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

and then for diffenet vals

然后对于不同的 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();
}

回答by genesis

Why would you do it? You can do something like

你为什么要这样做?你可以做类似的事情

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

but I DO NOT RECOMMEND IT. Use that first one. It's perfect and easy

我不推荐它。使用第一个。这是完美而简单的