jQuery在DOM中查找元素upper

时间:2014-05-07 09:02:52

标签: javascript jquery

我有以下结构:

<div class="content">

    <div class="author" data-id="1"></div>
    <div class="post"></div>    
    <div class="post"></div>  
    ...........................
    <div class="author" data-id="5"></div> // This is the target i need to get later
    <div class="post"></div>    
    <div class="post"></div>  

    <div class="author current" data-id="6"></div>
    <div class="post"></div>    
    <div class="post"></div>    
    <div class="post"></div>  
    .............................
    <div class="author" data-id="10"></div>
    <div class="post"></div>    
</div>

脚本:

$('.author.current').click(function(){
     var $current_author = $(this);
     var $prev_author = ...//Here i need to get the author div which is upper in the DOM tree(the one with comment)
     $current_author.removeClass('current')
     $prev_author.addClass('current')
})

正如我在代码中所写,我需要通过点击当前作者来获得前一作者。作者的数量可以是无限的。

有人可以帮我解决这个问题吗?感谢。

修改

感谢答案,正确的方法是:

 var $prev_author = $current_author.prevAll('.author').first()

1 个答案:

答案 0 :(得分:4)

尝试,

var $prev_author = $(this).prevAll('.author').first();

var $prev_author = $(this).closest('.content').find('.author:first');