[英]jquery function for individual divs
我認為可以使用.prev()
函數來實現,但是由於某些原因,它無法正常工作。
我正在為博客上的帖子創建拇指向上/向下按鈕。 我正在嘗試根據用戶的投票顯示消息。 UP或DOWN,但是每當我投票1條特定帖子時,該帖子就會出現在所有帖子中。
這是我的代碼。 我刪除了prev()使其更具可讀性的嘗試。 該腳本在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;
});
});
范例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>
編輯:提供的jsfiddle沒有Ajax部分http://jsfiddle.net/XJeXw/
您需要在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.