我有这个html结构:
<select class="required form-control parameter-criteria" selectpicker="" data-id="2" tabindex="-98">
<option value="1" data-content="<span class="badge-min filter d-inline-flex" style="background-color:#ff0000;"> </span>CRITERIO 1 [0 - 50] - CRITERIO 2" id-criteria="2">CRITERIO 1
</option>
</select>
<select class="required form-control parameter-criteria" selectpicker="" data-id="2" tabindex="-98">
<option value="1" data-content="<span class="badge-min filter d-inline-flex" style="background-color:#ff0000;"> </span>CRITERIO 1 [0 - 50] - CRITERIO 2" id-criteria="2">CRITERIO 1
</option>
</select>
我正在尝试选择一个特定的选择,所以我这样做了:
var select = $('.parameter-criteria[data-id=2]').eq(2);
这应该只返回最后选择的.eq(2)
,但是如果我打印select
会得到两个,为什么?
答案 0 :(得分:2)
这是因为eq()
索引是基于0的……就像第一个元素为0,第二个元素为1,依此类推。您只有两个匹配的元素,但是eq(2)
在列表中寻找不存在的第三个孩子并返回全部。
var select = $('.parameter-criteria[data-id=2]').eq(0);
console.log(select.text().trim());
var select2 = $('.parameter-criteria[data-id=2]').eq(1);
console.log(select2.text().trim());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="required form-control parameter-criteria" selectpicker="" data-id="2" tabindex="-98">
<option value="1" data-content="<span class="badge-min filter d-inline-flex" style="background-color:#ff0000;"> </span>CRITERIO 1 [0 - 50] - CRITERIO 2" id-criteria="2">CRITERIO 1
</option>
</select>
<select class="required form-control parameter-criteria" selectpicker="" data-id="2" tabindex="-98">
<option value="1" data-content="<span class="badge-min filter d-inline-flex" style="background-color:#ff0000;"> </span>CRITERIO 1 [0 - 50] - CRITERIO 2" id-criteria="2">CRITERIO 2
</option>
</select>