jQuery多选择器+ find()vs children()

时间:2012-12-03 15:30:25

标签: jquery jquery-selectors find children

<select id="select1">
    <option value="11">11</option>
    <option value="12">12</option>
</select>

<select id="select2">
    <option value="21">21</option>
    <option value="22">22</option>
</select>​

find()children()方法的行为:

find()

$('#select1, #select2').find('option:not(:first)').remove();​​​​​​

按预期工作:select1只有选项11select2只有选项21

children()

$('#select1, #select2').children('option:not(:first)').remove();

奇怪的是:select1只有11选项,但select2已无法选择......

为什么吗

Demo

2 个答案:

答案 0 :(得分:3)

我无法解释为什么.find正在使用:first,但.children无法与:first合作,因为:first获得第一个选定元素集中的选定元素,而不是第一个子元素。你想要的是:first-child

// children
$('#select1, #select2').children('option:not(:first-child)').remove();

// find
$('#select3, #select4').find('option:not(:first-child)').remove();​

演示:http://jsfiddle.net/tyZzy/2/

这可能是一个错误,但需要更多的研究。

答案 1 :(得分:2)

从我看到的

$('#select1, #select2').find('option:not(:first)')

等于

$('#select1  option:not(:first), #select2  option:not(:first)')

$('#select1, #select2').children('option:not(:first)')

考虑上下文选择器,因为它与使用.find()

相同
$('option:not(:first)',$('#select1, #select2'))

通过使用具有第一个...的子项,您只获得在集合中返回的第一个子选项..而context / find选择器在每个上下文中查找第一个

相关问题