简体   繁体   English

如何从点击目标中获取上一个元素?

[英]How to get previous element from click target?

Hello I have this html code: 您好,我有这个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>

When I click on img with id exit using this code 当我单击具有ID的img退出时使用此代码

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

}) })

I need to get the text of the <b> behind it which would be "this" 我需要在它后面加上<b>的文本,即"this"

I have tried this but it does not work: 我已经尝试过了,但是没有用:

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

It only gives me the that I clicked from the beginning 它只给我从一开始就点击的

try this: 尝试这个:

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

You can use $(this).closest('.row').find('b') : 您可以使用$(this).closest('.row').find('b')

 $('#exit').click(function(e){ $q = $(this).closest('.row').find('b'); var word = $q.text(); console.log(word); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="row newrow"> <div class="col-10"><b>this</b></div> <div class="col-2"> <img src="close.png" id="exit"/> </div> </div> 

You need to select the parent of the clicked img to get the the .col-2 , and then get the col-2 's prev() to get to the .col-10 , and then you can access its children() to get the children (the single <b> ). 您需要选择单击的img父级以获取.col-2 ,然后获取col-2prev()以获得.col-10然后可以访问其children()以得到孩子(单身<b> )。 Also, there's no need for e.target if you use this : 另外,如果您使用e.target则无需this

 $('body').on('click', '#exit', function() { $q = $(this).parent().prev().children(); var word = $q.text() console.log(word); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="row newrow"> <div class="col-10"><b>this</b></div> <div class="col-2"> <img src="close.png" id="exit" /> </div> </div> 

Try this 尝试这个

$('body').on('click','#exit',function(e){    
 var word = $(this).closest('.newrow').find('b').text();
 });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM