jQuery与类最接近的问题

kyl*_*lex 0 jquery closest

这是我的jQuery

$('.vote_down').live('click', function() {
    var $votes = $(this);
    var c_id = $(this).closest('.c_id').val();
    var c_vote = $(this).closest('.c_vote').val();
    $.ajax({
        type: "POST",
        url: "votes.php",
        data: "c_id="+c_id+"&c_vote="+c_vote,
        success: function(html){
            $votes.parent().html(html);             
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

以下是它的html:

vars c_id,c_vote目前一无所获

<div class="votes">
    <input type="hidden" class="c_id" value="5" />
    <input type="hidden" class="c_vote" value="2" />
    <img src="down_vote.png" border="0" class="vote_down" alt="Down Vote" />
</div>
Run Code Online (Sandbox Code Playgroud)

Fel*_*ing 5

您使用的是错误的功能.closest得到最近的祖先.输入字段不是图像的祖先,它们是兄弟姐妹.

你可以做:

var c_id = $(this).prevAll('.c_id').val();
var c_vote = $(this).prevAll('.c_vote').val();
Run Code Online (Sandbox Code Playgroud)

或者如果订单总是相同的:

var c_id = $(this).prev().prev().val();
var c_vote = $(this).prev().val();
Run Code Online (Sandbox Code Playgroud)

参考:prevAll,prev

  • +1 Yay!如果HTML翻转自己,你也可以使用`siblings()`:) (2认同)