jQuery 嵌套的选择器 <p>

jQuery selector of nested <p>

谁知道为什么这行不通:

$( "p  p" ).each(function() {
    $(this).css("color", "green");
});

以及 "p > p",或任何具有嵌套段落元素的内容。虽然 div 和其他元素

没问题

例如检查这个:

<script src="https://code.jquery.com/jquery-1.10.2.js"></script>

<script>
  alert('length='+$('p p').length); // 0
</script>

<div style="border:1px solid;">
  <p>The first paragraph in  div.</p>
  <p>The second paragraph in div (and the 2nd child in this div).</p>
  <p>
    <span>Span within p (WILL BE fount as "p > span")</span>
    <p>P within p (1).</p> 
    <span>Span within p (will NOT be fount as "p > span")</span>
    <p>P within p (2).</p>
  </p>
</div>
<p>
    <span>Span within p (WILL BE fount as "p > span")</span>
    <p>P within p (1).</p> 
    <span>Span within p (will NOT be fount as "p > span")</span>

只需将您的 P 标签更改为 SPAN 即可:

jQuery("span").find('span').each(function() {
    jQuery(this).css("color", "green");
});

这是工作演示https://jsfiddle.net/0gqL9q3c/

如果您在调试工具中检查呈现的 html,您会发现,您嵌套的 <p> 元素的 none 不再嵌套。它们呈现为单独的元素。所以我 html 呈现并且您将使用 $('p p')$('p>p') 操作 DOM,不存在具有上述表达式或 [=22= 指定语法的元素] 操纵。

<div style="border:1px solid;">
  <p>The first paragraph in  div.</p>
  <p>The second paragraph in div (and the 2nd child in this div).</p>
  <p>
    <span>Span within p (WILL BE fount as "p &gt; span")</span>
    </p><p>P within p (1).</p> 
    <span>Span within p (will NOT be fount as "p &gt; span")</span>
    <p>P within p (2).</p>
  <p></p>
</div>
<p>
    <span>Span within p (WILL BE fount as "p &gt; span")</span>
    </p><p>P within p (1).</p> 
    <span>Span within p (will NOT be fount as "p &gt; span")</span>

@Ish和@j08691提到的<p>标签不能嵌套,你可以借助浏览器的调试工具在浏览器中看清楚。 如需更多参考,请查看另一个 SO 答案