如何基于多个属性选择特定选项?

时间:2018-12-11 09:19:35

标签: javascript jquery

假设我有这个选择:

<select class="required form-control parameter-criteria" selectpicker="" data-id="2" tabindex="-98">
    <optgroup label="criterio 2">
        <option value="1" data-content="<span class=&quot;badge-min filter d-inline-flex&quot; style=&quot;background-color:#ff0000;&quot;> </span>CRITERIO 1 [0 - 50] - CRITERIO 2" id-criteria="2">CRITERIO 1
        </option>
       <option value="2" data-content="<span class=&quot;badge-min filter d-inline-flex&quot; style=&quot;background-color:#ffb700;&quot;> </span>CRITERIO 2 [51 - 60] - CRITERIO 2" id-criteria="2">CRITERIO 2
       </option>
       <option value="3" data-content="<span class=&quot;badge-min filter d-inline-flex&quot; style=&quot;background-color:#66ff00;&quot;> </span>CRITERIO 3 [61 - 100] - CRITERIO 2" id-criteria="2">CRITERIO 3
       </option>
     </optgroup>
</select>

我试图选择具有id-criteria=2value = 3的选项,所以我这样做了:

$('.parameter-criteria[data-id=2]')
   .find('option[value=3]')
   .find('id-criteria', 2).prop('selected', true);

但这行不通,知道吗?

1 个答案:

答案 0 :(得分:1)

您可以将两个条件都指定为.find('option[value=3][id-criteria=2]')

$('.parameter-criteria[data-id=2]')
   .find('option[value=3][id-criteria=2]')
   .prop('selected', true);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<select class="required form-control parameter-criteria" selectpicker="" data-id="2" tabindex="-98">
    <optgroup label="criterio 2">
        <option value="1" data-content="<span class=&quot;badge-min filter d-inline-flex&quot; style=&quot;background-color:#ff0000;&quot;> </span>CRITERIO 1 [0 - 50] - CRITERIO 2" id-criteria="2">CRITERIO 1
        </option>
       <option value="2" data-content="<span class=&quot;badge-min filter d-inline-flex&quot; style=&quot;background-color:#ffb700;&quot;> </span>CRITERIO 2 [51 - 60] - CRITERIO 2" id-criteria="2">CRITERIO 2
       </option>
       <option value="3" data-content="<span class=&quot;badge-min filter d-inline-flex&quot; style=&quot;background-color:#66ff00;&quot;> </span>CRITERIO 3 [61 - 100] - CRITERIO 2" id-criteria="2">CRITERIO 3
       </option>
     </optgroup>
</select>