Del*_*D0D 2 html javascript jquery 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>
Run Code Online (Sandbox Code Playgroud)
我试过了:
$("body").on('click', '.myClass', function() {
var text=$(this).closest( "h1" ).html();
alert(text);
});
Run Code Online (Sandbox Code Playgroud)
但text最终undefined因为找不到h1标签
预期结果:函数应警告"这是标题1"
closest应该用来获取元素的最近父元素,然后获得前一个兄弟:
var text = $(this).closest('div').prev('h1').text();
Run Code Online (Sandbox Code Playgroud)
演示: http ://jsfiddle.net/son6v8g3/3/
| 归档时间: |
|
| 查看次数: |
1529 次 |
| 最近记录: |