<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/
这可能是一个错误,但需要更多研究。
关于jQuery 的多重选择器 + find() 与 Children(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13686415/