简体   繁体   English

jQuery-选择“ h1”或“ h2”下方的所有文本

[英]jQuery - select all text “underneath” a h1 or h2

Say I have a document with a mixture of <h1> , <h2> <h3> etc, plus other elements like <p> . 假设我有一个文档,其中包含<h1><h2> <h3>等,以及其他元素,如<p>

from the DOM perspective, each element is sat directly under the <body> , but obviously from a semantic perspective, the elements are nested by heading level 从DOM的角度来看,每个元素都直接位于<body> ,但显然从语义的角度来看,这些元素是按标题级别嵌套的

I'm trying to implement some kind of slideUp/slideDown outline expander so when the user clicks an h2, for example, I need to search down the document until I find another heading of level h2 or better, and then collect all the elements in between as being the content which is semantically "under" that h2. 我正在尝试实现某种slideUp / slideDown轮廓扩展器,因此,例如,当用户单击h2时,我需要向下搜索文档,直到找到h2或更高级别的另一个标题,然后收集其中的所有元素。之间是在语义上位于“ h2”之下的内容。

at the moment, I'm assuming I'll just have to wrap it all in nested divs to make the DOM tree nesting match the semantics, but is there any way to avoid that? 目前,我假设我只需要将它们全部包装在嵌套的div中,以使DOM树嵌套与语义相匹配,但是有什么办法可以避免这种情况?

You can use nextUntil() for that 您可以使用nextUntil()

$("h2").click(function(){
  $(this).nextUntil("h2")
});

Demo 演示

you dont need to use any divs to wrap the elements, just use .nextUntil(...) like this 您不需要使用任何div来包装元素,只需使用.nextUntil(...)这样

Jquery Code: jQuery代码:

$('h2').on('click',function (){
       var dom=$(this).nextUntil('h2');
       if($(dom).is(":hidden")){
            $(dom).show(); 
       }
       else{
            $(dom).hide(); 
       }           
});

Ref: http://api.jquery.com/nextuntil/ 参考: http : //api.jquery.com/nextuntil/

Live Demo 现场演示

http://jsfiddle.net/dreamweiver/vag2r/3/ http://jsfiddle.net/dreamweiver/vag2r/3/

Happy Coding :) 快乐编码:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM