我对 jQuery 中的元素选择如何使用children()和:first自定义类感到困惑?
例如,在这个 jsFiddle中,代码ul > li {hello from nest}没有得到类.emphasis,但first-child顶层ul得到了它。我希望内部li也能上课。
我的 jQuery 代码中注释掉的行按我的预期工作。
我对 jQuery 中的元素选择如何使用children()和:first自定义类感到困惑?
例如,在这个 jsFiddle中,代码ul > li {hello from nest}没有得到类.emphasis,但first-child顶层ul得到了它。我希望内部li也能上课。
我的 jQuery 代码中注释掉的行按我的预期工作。
:first选择器返回所有选定项中的第一个匹配项
所以
$('ul').children('li:first').addClass('emphasis');
ul选择其中的所有孩子,li然后取其中的第一个。
然而
$('ul > li:first-child').addClass('emphasis');
获取所有li直接子节点,ul并获取匹配集的每个第一个子节点。
jQuery go throw the DOM Tree 并在这个 Tag中找到第一个ul-Tag ,它会得到你制作的 CSS。first-childli
所以这意味着它们中的第一个。
使用ul > li:first-childjQuery 时,每个 li 都是每个 li 的第一个孩子,ul而不仅仅是第一个。