首页 > 解决方案 > 如何从点击目标中获取上一个元素?

问题描述

你好我有这个html代码:

<div class="row newrow">
        <div class="col-10"><b>this</b></div>
        <div class="col-2">
            <img src="close.png" id="exit"/>
        </div>
    </div>

当我使用此代码单击带有 id 退出的 img

$('body').on('click','#exit',function(e){

})

我需要得到<b>它背后的文字,这将是"this"

我已经尝试过了,但它不起作用:

$('body').on('click','#exit',function(e){    
 $q = $(e.target).prev('b')
       var word = $q.text()
)}

它只给了我从一开始就点击的那个

标签: javascriptjqueryhtml

解决方案


试试这个:

$('body').on('click','#exit',function(e){    
   var this_b = $(this).parent().prev().children(0).html();// get the text
   alert(this_b);
});

推荐阅读