【问题标题】:jQuery - remove select option based on text not valuejQuery - 基于文本而不是值删除选择选项
【发布时间】:2014-08-30 16:24:53
【问题描述】:

我有一个下拉框如下:

<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>

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

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

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

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

【问题讨论】:

    标签: jquery select option


    【解决方案1】:

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

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

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

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

    【讨论】:

    • IE11 不支持,请帮帮我。
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2021-10-15
      • 2012-11-29
      • 1970-01-01
      • 2023-04-02
      • 2011-11-06
      • 2012-05-14
      • 2023-03-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多