只选择一个最接近的元素

时间:2014-10-27 11:20:45

标签: javascript jquery

我使用jQuery选择一个最接近的元素时遇到问题。

我的HTML代码

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

点击图片.details后,我想从.doAction获取文字

但问题是我有多次使用相同的HTML代码,因此我希望最接近此img .details文字。

我该怎么做?

3 个答案:

答案 0 :(得分: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/

答案 1 :(得分:1)

您还可以将.parents().next().find()

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

Demo

在这里,我选择tr标记的父img class .doAction,然后转到下一个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 */

答案 2 :(得分:0)

使用.closest()遍历表格,然后找到包含.details的td:

 $('.doAction').click(function(){
   $(this).closest('table').find('.details').text();
 });
相关问题