jQuery's multiple selector + find() vs children()

落花浮王杯 提交于 2019-12-08 03:02:20

问题


<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>​

Behavior of the find() and the children() methods:

find():

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

Works as expected: select1 has only option 11 and select2 has only option 21

children():

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

Works weirdly: select1 has only option 11 but select2 has no option anymore...

Why?

Demo


回答1:


From what I see

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

is equal to

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

not

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

Think about the context selector as it's the same as using .find()

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

By using children with first.. you are only getting the first children option returned in collection.. whereas the context/find selector looks for the first in each context




回答2:


I can't explain why the .find is working with :first, but the .children isn't working with :first because :first gets the first selected element in the set of selected elements, not the ones that are the first child. What you want is :first-child.

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

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

Demo: http://jsfiddle.net/tyZzy/2/

This may be a bug, though it needs more research.



来源:https://stackoverflow.com/questions/13686415/jquerys-multiple-selector-find-vs-children

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!