简体   繁体   English

在单击元素之前获取最后一个h1标记

[英]Get last h1 tag before clicked element

When a user clicks an element on a page, I need to find the closest h1 tag above the clicked element and get it's html content. 当用户单击页面上的元素时,我需要在单击的元素上方找到最接近的h1标记并获取它的html内容。

Given the below html: 鉴于以下html:

<div>
  <h1>This is header 1</h1>
  <div>
     <span> some text</span><br>
     <span> some text</span><br>
     <span> some text</span><br>
     <span style="color:red;" class="myClass"> CLICK ME</span><br>
     <span> some text</span><br>
     <span> some text</span><br>
  </div>
   <h1>This is header 2</h1>
  <div>
     <span> some text</span><br>
     <span> some text</span><br>
     <span> some text</span><br>
     <span> some text</span><br>
     <span> some text</span><br>
     <span> some text</span><br>
  </div>
</div>

I tried: 我试过了:

$("body").on('click', '.myClass', function() {

        var text=$(this).closest( "h1" ).html();
        alert(text);

});

But text ends up undefined as it doesn't find the h1 tag text最终undefined因为它找不到h1标签

Expected result: function should alert "This is header 1" 预期结果:函数应警告“这是标题1”

jsfiddle 的jsfiddle

closest should be used to get the closest parent of the element, then get the previous sibling : closest应该用于获得元素的最近元素,然后得到前一个兄弟

var text = $(this).closest('div').prev('h1').text();

DEMO: http://jsfiddle.net/son6v8g3/3/ 演示: http //jsfiddle.net/son6v8g3/3/

您也可以使用父母

 var heading = $(this).parents('div:first').prev('h1').text()

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

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