如何定位平面层次结构中的特定兄弟姐妹组? [英] How can I target a specific group of siblings in a flat hierarchy?

查看:17
本文介绍了如何定位平面层次结构中的特定兄弟姐妹组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设你有这个 HTML:

Assume you have this HTML:

<h1>Header 1</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<h1>Header 1</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<h1>Header 1</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>

请注意,层次结构是扁平的.

Note that the hierarchy is flat.

现在尝试选择 <p> 元素的中间对".这可能吗?我实在想不通.

Now try to select the "middle pair" of <p> elements. Is this possible? I really can't figure out how.

这个选择器只抓取<h1>之后的第一个<p>:

This selector only grabs the first <p> following the <h1>:

h1:nth-of-type(2) + p

但是这个选择器会抓取正确的一对 <p> 元素加上所有出现在后面的 <p> 元素我们想要的一对:

But this selector grabs the correct pair of <p> elements plus all the following <p> elements that appear after the pair we want:

h1:nth-of-type(2) ~ p

有可能吗?

没有 JavaScript.没有标记更改.通用解决方案.允许任意数量的 <h1>s 或 <p>s,在这种情况下,数字 2 是任意的.

No JavaScript. No markup changing. Generic solution. Any number of <h1>s or <p>s are allowed, and the number two, in this case, is arbitrary.

我在想也许这可以使用一些使用 :not() 选择器,但我似乎无法弄清楚.有点像选择一般兄弟姐妹",然后根据需要排除,或类似的东西.

I'm thinking maybe this is possible using some using the :not() selector, but I can't seem to figure it out. Kind of like selecting the "general siblings" and then excluding as necessary, or something similar.

推荐答案

由于一般同级组合器的工作方式,不可能将同级的选择限制在特定范围或组中,即使是连续的同级.甚至 :not() 选择器在这里也没有任何帮助.

Due to the way the general sibling combinator works, it is not possible to limit a selection of siblings to a specific range or group, even of consecutive siblings. Even the :not() selector won't be of any help here.

必须使用 JavaScript 来定位正确的元素.jQuery 的 .nextUntil() 方法 立即浮现在脑海中.

You will have to use JavaScript to target the right elements. jQuery's .nextUntil() method immediately springs to mind.

这篇关于如何定位平面层次结构中的特定兄弟姐妹组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆