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

时间:2014-09-01 10:19:46

标签: javascript jquery html dom closest

当用户点击页面上的元素时,我需要在点击的元素上方找到最接近的h1标记并获取它的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>

我试过了:

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

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

});

但是text最终undefined,因为它找不到h1标签

预期结果:功能应提醒“这是标题1”

jsfiddle

2 个答案:

答案 0 :(得分:7)

closest应该用于获取元素中最接近的,然后获取previous sibling

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

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

答案 1 :(得分:1)

您也可以使用parents

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