【问题标题】:Jquery selector to get dropdown by its valueJquery 选择器按其值获取下拉列表
【发布时间】:2018-12-21 19:32:00
【问题描述】:

我找不到找到具有特定值的下拉列表的方法。

ex1:

$('[value="' + $(e.currentTarget).attr('name') + '"]')

给我带有值的选项。

ex2:

$('[value="' + $(e.currentTarget).attr('name') + '"]').parent()

给我正确的下拉菜单。但是,如果我有多个具有相同值的选项的 <select> 元素,我会得到更多结果。

无法按值找到<select> 元素?

提前致谢

【问题讨论】:

    标签: jquery select jquery-selectors selector


    【解决方案1】:

    :has() selector 可用于定位SELECT:selected selector 用于选择的选项。

    选择包含至少一个与指定选择器匹配的元素的元素。

    var selects = $('select:has(option:selected[value="' + $(e.currentTarget).attr('name') + '"])');
    

    var v = 1;
    var selects = $('select:has(option:selected[value="' + v + '"])')
    selects.css('color', 'green')
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <select>
      <option value="0">0</option>
      <option value="1">1</option>
    </select>
    <select>
      <option value="2">2</option>
    </select>
    <select>
      <option value="0">0</option>
      <option value="1" selected>1</option>
    </select>

    或者,使用.filter()

    var selects = $('select').filter(function() {
       return $(this).val() == $(e.currentTarget).attr('name');
    });
    

    var v = 1;
    var selects = $('select').filter(function() {
      return $(this).val() == 1;
    });
    selects.css('color', 'green')
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <select>
      <option value="0">0</option>
      <option value="1">1</option>
    </select>
    <select>
      <option value="2">2</option>
    </select>
    <select>
      <option value="0">0</option>
      <option value="1" selected>1</option>
    </select>

    【讨论】:

    • 我想通过当前选定选项的值来获取选择...而不是选项
    • 对不起,不是选择具有值的选项,而是选择具有该值的选择
    • @LeonelMatiasDomingos,更新答案
    猜你喜欢
    • 2011-07-06
    • 1970-01-01
    • 1970-01-01
    • 2013-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多