2010-11-23 6 views
1

これは.prev()関数で実現できると思っていましたが、何らかの理由で機能しません。個々のdivのjquery関数

私は、ブログ上の投稿のための親指の上/下ボタンを作成しています。私はユーザーが投票した内容に応じてメッセージを表示しようとしています。 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> 

EDIT: http://jsfiddle.net/XJeXw/

+1

あなただけの数の 'class'または' id'属性を作るべきではありません。彼らは決して数字で始めるべきではありません。 – alex

+0

それは良い情報です。私はそれを修正するつもりです。 – CyberJunkie

答えて

5

あなたはclickハンドラ内のボタンへの参照を保存する必要がある(例えば、var me = $(this);)、その後、使用Ajaxの部分なしで提供jsfiddle me.nextAll('.msg_box:first')をAJAXハンドラの内側に配置します。

EDITExample

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); 
    } 
}); 
+0

完全に機能するスラーク!どうもありがとうございます!将来のスクリプトのためにあなたのコードを覚えています。 if文の改訂にも感謝します。 Bonus noobに関する質問:varという名前をつけた特別な理由はありますか? – CyberJunkie

+0

@Cyber​​:いいえ「自己」と「それ」も共通しています。 ''これはオプションではない、(うまくいけば)明白な理由のために。 – SLaks

+0

ああ、はい。再度、感謝します! – CyberJunkie

関連する問題