<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
只有选项11
,select2
只有选项21
children()
:
$('#select1, #select2').children('option:not(:first)').remove();
工作很奇怪:select1
只有11
选项,但select2
没有选择......
为什么?
演示
我无法解释为什么.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/
这可能是一个错误,尽管它需要更多的研究。
据我所知
$('#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'))
通过将 child 与 first. 一起使用,您只会获得集合中返回的第一个子选项,而上下文/查找选择器在每个上下文中查找第一个选项。