Javascript 获取单击元素之前的最后一个h1标记
当用户单击页面上的某个元素时,我需要在单击的元素上方找到最近的Javascript 获取单击元素之前的最后一个h1标记,javascript,jquery,html,dom,closest,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 te
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
由于找不到h1标记而导致undefined
预期结果:函数应提醒“这是标题1”
最近的
应用于获取元素的最近父元素,然后获取:
演示:您也可以使用
父母
显然是过火了。
var text = $(this).closest('div').prev('h1').text();
var heading = $(this).parents('div:first').prev('h1').text()