2014-10-27 85 views
2

我有问题,通过使用jQuery选择一个最接近的元素。选择一个最接近的元素

我的HTML代码

<table> 
    <tbody> 
     <tr>   
      <td> 
       <span class="control"><img class="doAction"></span> 
      </td> 
     </tr> 
     <tr>  
      <td class="details">sometext</td> 
     </tr> 
    </tbody> 
</table> 

我想点击图片.doAction

但问题后获得来自.details文字,我有多次这种相同的HTML代码,所以我只要最接近这个img.details文字即可获得。

我该怎么做?

回答

1

您还可以使用.parents().next().find()

$('.doAction').on('click', function() { 
    console.log($(this).parents('tr').next().find('.details').text()); 
}); 

Demo

在这里,我选择img标签的父tr.doAction一个class,然后我移动到下一个tr.details

请注意,这是.parent(s),如果你想你搜索元素还可以使用.parent()但你需要三次使用它,就像

$(this).parent().parent().parent().next().find('.details').text(); 
/*   --^--  --^-- --^-- --^-- 
    Selects span  td  tr goes to next tr and then finds for .details 
                  and returns text */ 
+0

该解决方案完美的作品,谢谢! – user3033997 2014-10-27 11:37:44

0

使用.closest()遍历表,然后找到.details TD在它:

$('.doAction').click(function(){ 
    $(this).closest('table').find('.details').text(); 
}); 
1
$('.doAction').click(function(i, e) 
{ 
    e.closest('table').find('.details').html(); 
}); 

注:另一种方法是遍历到tr只,拿到下一个兄弟,然后得到那里的.details。这可能是更精确,你可能有几个这样的.doAction.details元素在里面:

$('.doAction').click(function(i, e) 
{ 
    e.closest('tr').next().find('.details').html(); 
}); 

参考:

http://api.jquery.com/closest/