I thought this could be achieved with the .prev()
function but for some reason it isn't working.
I'm creating thumbs up/down buttons for posts on a blog. I'm trying to display messages according to what the user votes. Either UP or DOWN but whenever I vote 1 particular post, the message appears for all the post.
This is 开发者_JAVA技巧my code. I removed the prev() attempts to make it more readable. The script works fine ajax wise.
$(document).ready(function() {
$(".vote_button").click(function(e) { //the UP or DOWN vote button
var vote_status = $(this).attr('class').split(' ')[1]; //gets second class name following vote_button
var vote_post_id = $(this).attr("id"); //the post ID
var dataString = 'post_id=' + vote_post_id + '&vote_status=' + vote_status;
$.ajax({
type: "POST",
url: "url/add_vote.php",
data: dataString,
cache: false,
success: function(html) {
if (vote_status == 1)
{
$('.msg_box').fadeIn(200);
$('.msg_box').text('You voted UP!');
}
if (vote_status == 2)
{
$('.msg_box').fadeIn(200);
$('.msg_box').text('You voted DOWN!');
}
}
});
return false;
});
});
Sample HTML
<div class="vote_button 1" id="18">UP</div>
<div class="vote_button 2" id="77">DOWN</div>
<div class="msg_box"></div>
<div class="vote_button 1" id="43">UP</div>
<div class="vote_button 2" id="15">DOWN</div>
<div class="msg_box"></div>
<div class="vote_button 1" id="11">UP</div>
<div class="vote_button 2" id="78">DOWN</div>
<div class="msg_box"></div>
EDIT: Provided jsfiddle without Ajax part http://jsfiddle.net/XJeXw/
You need to save a reference to the button inside the click
handler (eg, var me = $(this);
), then use me.nextAll('.msg_box:first')
inside the AJAX handler.
EDIT: Example:
var me = $(this); //The this will be different inside the AJAX callback
$.ajax({
type: "POST",
url: "url/add_vote.php",
data: dataString,
cache: false,
success: function(html) {
me.nextAll('.msg_box:first')
.text(vote_status == 1 ? 'You voted UP!' : 'You voted DOWN!')
.fadeIn(200);
}
});
精彩评论