【问题标题】:jQuery selector of nested <p>嵌套 <p> 的 jQuery 选择器
【发布时间】:2017-01-07 06:42:33
【问题描述】:

谁知道为什么这行不通:

$( "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>

【问题讨论】:

  • 你不能嵌套&lt;p&gt;元素

标签: jquery jquery-selectors nested paragraphs


【解决方案1】:

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

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

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

【讨论】:

  • 问题是关于为什么嵌套 p 不起作用,而不是关于它的另一个解决方法@user
【解决方案2】:

如果您在调试工具中检查渲染的 html,您会发现,您嵌套的 &lt;p&gt; 元素都不再嵌套。它们被渲染为一个单独的元素。所以我的 html 呈现,你将使用 $('p p')$('p&gt;p') 操作 DOM,不存在具有上述表达式或 DOM 操作语法的元素。

<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 所说,&lt;p&gt; 标签不能嵌套,您可以借助浏览器的调试工具在浏览器中清楚地看到。 如需更多参考,请查看另一个SO 答案

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多