jQuery - 基于文本而不是值删除选择选项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24657154/
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-27 02:37:40  来源:igfitidea点击:

jQuery - remove select option based on text not value

jqueryselectoption

提问by odd_duck

I have a dropdown box as follows:

我有一个下拉框,如下所示:

<select id="select_Boiler">
  <option value="boiler_1645">Vaillant 831</option>
  <option value="boiler_2373">Worcester 24</option>
  <option value="boiler_3009">Vaillant 835</option>
  <option value="boiler_4354">Bosch 671</option>
</select>

I need to be able remove specific options using jQuery but based on the text not the option value. I've tried this without success:

我需要能够使用 jQuery 删除特定选项,但基于文本而不是选项值。我试过这个没有成功:

jQuery("#select_Boiler option[text='Vaillant 835']").remove();

I know I can do the same with value as below and it works but i need to do it by text

我知道我可以用下面的值做同样的事情并且它有效,但我需要通过文本来做

jQuery("#select_Boiler option[value='boiler_3009']").remove();

回答by Arun P Johny

you can use :containsto filter based on text content of an element, but note that it will return partial matches. So :contains('Vaillant 835')will return :contains('Vaillant 835')and :contains('Vaillant 8356')

您可以使用:contains根据元素的文本内容进行过滤,但请注意,它将返回部分匹配项。因此,:contains('Vaillant 835')将返回:contains('Vaillant 835'):contains('Vaillant 8356')

jQuery("#select_Boiler option:contains('Vaillant 835')").remove();

If you want to filter for equal you need to do a manual filter like

如果你想过滤相等你需要做一个手动过滤器

jQuery("#select_Boiler option").filter(function(){
    return $.trim($(this).text()) ==  'Vaillant 835'
}).remove();

回答by Svetoslav Marinov

Here's the case insensitive option of Arun P Johny's answer.

这是 Arun P Johny 回答的不区分大小写的选项。

jQuery("#select_Boiler option").filter(function() {
    cur_text = $(this).text().trim().toLowerCase();
    return cur_text.indexOf('Vaillant 835') != -1;
}).remove();