当用户点击页面上的元素时,我需要在点击的元素上方找到最接近的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”
答案 0 :(得分:7)
closest
应该用于获取元素中最接近的父,然后获取previous sibling:
var text = $(this).closest('div').prev('h1').text();
答案 1 :(得分:1)
您也可以使用parents
var heading = $(this).parents('div:first').prev('h1').text()