[英]jquery function for individual divs
I thought this could be achieved with the .prev()
function but for some reason it isn't working. 我认为可以使用
.prev()
函数来实现,但是由于某些原因,它无法正常工作。
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.
UP或DOWN,但是每当我投票1条特定帖子时,该帖子就会出现在所有帖子中。
This is my code. 这是我的代码。 I removed the prev() attempts to make it more readable.
我删除了prev()使其更具可读性的尝试。 The script works fine ajax wise.
该脚本在ajax方面运行良好。
$(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 范例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/ 编辑:提供的jsfiddle没有Ajax部分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. 您需要在
click
处理程序中保存对按钮的引用(例如, var me = $(this);
),然后在AJAX处理程序中使用me.nextAll('.msg_box:first')
。
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);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.