2010-11-23 3 views
1

이 작업은 .prev() 함수를 사용하여 수행 할 수 있다고 생각했지만 어떤 이유로 작동하지 않습니다.개별 divs에 대한 jquery 함수

블로그의 게시물에 대해 위로/아래로 버튼을 만듭니다. 사용자가 투표 한 내용에 따라 메시지를 표시하려고합니다. UP 또는 DOWN 중 하나를 선택하면 특정 게시물 1 개를 투표 할 때마다 모든 게시물에 대해 메시지가 나타납니다.

이것은 내 코드입니다. 더 읽기 쉽도록 prev() 시도를 제거했습니다. 스크립트 잘 아약스 현명한 작동합니다.

$(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> 

편집 : http://jsfiddle.net/XJeXw/

+1

당신은 id' 그냥 숫자 속성의''class'를하거나해서는 안된다. 그들은 숫자로 시작해서는 안됩니다. – alex

+0

좋은 정보입니다. 나는 그것을 고칠 것이다. – CyberJunkie

답변

5

당신은 click 핸들러 내부의 버튼에 대한 참조를 저장해야합니다 (예를 들어, var me = $(this);), 다음 사용 아약스 부분없이 제공 jsfiddle me.nextAll('.msg_box:first') AJAX 처리기 안에.

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

완벽하게 작동하는 슬랙! 정말 고맙습니다! 나는 미래 스크립트를위한 코드를 확실히 기억할 것이다. if 문 개정에 감사드립니다. 보너스 멍청한 질문 : var라는 이름을 가진 특별한 이유가 있습니까? – CyberJunkie

+0

@Cyber ​​: 아니요. '자기'와 'that'도 일반적입니다. 'this'는 (희망 적으로) 명백한 이유 때문에, 선택 사항이 아닙니다. – SLaks

+0

아, 네. 다시 한 번 감사드립니다! – CyberJunkie