jquery - 选择不是当前元素/JQuery 父级的先前标题

标签 jquery html select html-heading

我有以下标记

<div id="section1">
  <h1>Titel 1</h1>
  <p>Some smart Text</p>
</div>
<div id="section2"> 
  <h2>Titel 2</h2>
  <p>Some smart Text2</p>
</div>
<div id="section3-1">
  <h3>Titel 3-1</h3>
</div>
<div id="section3-1content">
  <ul>
     <li id="section3-1content-el1">El1</li>
     <li id="section3-1content-el2">El2</li>
  </ul>
</div>
<div id="section3-2">
  <h3>Titel 3-2</h3>
</div>
<div id="section3-2content">
  <ul>
     <li id="section3-2content-el1">El1</li>
     <li id="section3-2content-el2">El2</li>
  </ul>
</div>

当我点击#section3-2content-el2 时我想返回

 <h3>Titel 3-2</3>

(最近的h3),然后

 <h2>Titel 2</h2> 

然后

 <h1>Titel 1</h1>.

问题在于,h3、h2 和 h1 并不是被单击元素的真正父元素。有什么方法可以返回源代码并找到第一个 h3,然后是第一个 h2,然后是第一个 h1?

问题在于:

$('#section3-2content-el1').click(function(){
  $('#section3-2content-el1').parents('h3');
  $('#section3-2content-el1').prevAll('h3');
  $('#section3-2content-el1').closest('h3');
});

是他们都沿着 dom 向上移动并查看是否有一个是 h3。但是 h3 不是被点击元素的父元素。

最佳答案

Demo Fiddle

有很多选择。考虑到您的 html 结构 :last 是最佳选择。查看演示。

$(this).parents('body').find('h3:last')

如果您的标题标签是一致的,.prev() 将是另一种选择。

关于jquery - 选择不是当前元素/JQuery 父级的先前标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24246575/

相关文章:

PHP DOM 解析器移动关闭 Div 标记

javascript - 如何更改我的 js 代码以使菜单正常工作

mysql - 将复杂的 count() 查询结果插入表中

php - 如何在 MYSQL 查询中的另一个计算中立即使用计算结果

javascript - JQuery,创建多个具有升序ID的html元素?

javascript - CodeMirror 在更改事件上合并构造函数

jquery - 使用jquery获取动态创建的文本框的值

javascript - 我应该如何实现这个jquery插件?

html - 你如何使 css-transformation 看起来像 3d?

MySql 转换选择查询以更新