折叠所有后续元素,直到特定标记

Collapse all following elements until specific tag

本文关键字:元素 折叠      更新时间:2023-09-26

我有一个带有自升标记的常见问题解答,如下所示:

<p><strong>How can I come see the animals perform?</strong><br>
Schedules and information about attending a performance can be found here:</p>
<p><a href="http://jupmingdolphins.com">Performance tickets</a></p>
<p>If no performances are listed, it means that none are scheduled in the
near future. The animals take a break between November and May.</p>
<p><strong>What's the answer to this question?</strong><br>
It's 42, of course.</p>
<h2>Header for More Questions</h2>
<p><strong>Is it true the dolphins have smartphones?</strong><br>
Yes, they use Android phones and text each other constantly.</p>
<p><b>Just kidding!</b> They are all Apple fan-fish and prefer iPhones.</p>
(etc)

我试图弄清楚:

  1. 一些CSS(可能还有jQuery)在页面加载时隐藏除问题之外的所有内容。

  2. 简单的jQuery,当用户单击一个<strong>包装的问题时,答案会向下滑动并出现在它下面。正如你所看到的,问题是标记很古怪(感谢CMS),一个问题和另一个问题之间可能有很多东西。答案没有包含在他们自己的 DIV 或任何东西中。最重要的是,整个FAQ都有H2子标题,我不希望H2被触摸/折叠。

所以我需要类似于点击操作的代码:

$('strong').click(function() {
   // hide or reveal all elements from $(this) down,
   // and stop when we hit next <strong> or <h2>
});

Edit

由于问题甚至没有自己的标签,这变得非常复杂。 因此,您需要隐藏问题的父标签,但显示问题本身,这基本上是不可能的。

为了解决这个问题,这里有一个我整理的黑客。 它克隆问题并将它们附加到自己的标签中。 但是,我建议尝试说服此标记的作者将其修改为更合理的东西。


为了隐藏非问题,看起来您可以使用以下内容:

$("#container").children().not($("strong").parent()).not("p").hide();

为了显示答案,您可以使用nextUntil

$(this).parent().nextUntil($("strong").parent()).show();

小提琴