jQuery closest problem with classes
Here is my 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);
}
});
});
And here is the html it's pulling from:
The vars c_id
and c_vote
currently get nothing
<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>
You are using the wrong function. closest
gets the closest ancestor. The input fields are not ancestors of the image, they are siblings.
You can do:
var c_id = $(this).prevAll('.c_id').val();
var c_vote = $(this).prevAll('.c_vote').val();
or if the order is always the same:
var c_id = $(this).prev().prev().val();
var c_vote = $(this).prev().val();
Reference: prevAll
, prev
$('.vote_down').live('click', function() {
var $votes = $(this);
var c_id = $(this).prev('input.c_id:first').val();
var c_vote = $(this).prev('input.c_vote:first').val();
$.ajax({
type: "POST",
url: "votes.php",
data: "c_id="+c_id+"&c_vote="+c_vote,
success: function(html){
$votes.parent().html(html);
}
});
});
-edited after your comment, true my bet, I ment prev()- If you always use this HTML structure, why not use prev(); ? Try the above code
精彩评论