jquery get neighbor html value

jquery get neighbor html value

本文关键字:value html neighbor get jquery      更新时间:2023-09-26

我有以下html

<div class="wrapper">
    <h5>Testing</h5>
    <ul>
        <li><span class='ent'>test</span></li>
        <li><span class='ent'>test</span></li>
    </ul>
</div>
<div class="wrapper">
    <h5>Testing123</h5>
    <ul>
        <li><span class='ent'>test</span></li>
        <li><span class='ent'>test</span></li>
    </ul>
</div>

我有一个点击功能

$('.ent').on('click', function() {
    alert($(this).html()); #This works fine
    alert($(this).find('h5').html()) #This is undefined
})

我可以假设这是引用当前元素,但是我如何获取邻居元素html。

尝试

alert($(this).closest('ul').prev('h5').html());

alert($(this).parent().prev('h5').html());

alert($(this).closest('.wrapper').find('h5').html());


你的代码有问题.find()向下看你的元素h5上面的树,所以你需要使用类wrapper获取父element而不是使用find或获取父ul并使用.prev()获取前一个元素
参考

.closest()

.parent()

.prev()

.find()