2013-02-16 2 views
1

2 개의 버튼이 있으며이 2 개의 버튼은 총 클릭 수를 증가시킵니다. (합계는 별도로 계산됩니다.) 사용자는 하나만 선택할 수 있습니다. 이는 이전에 buttonA를 클릭하고 buttonB를 다시 클릭 한 경우를 의미합니다. ButtonA가 -1이고 ButtonB가 +1됩니다.2 개의 버튼 사이의 증가 및 감소

다음 코드가 있는데 문제가 있습니다. 더는 사용자가 buttonA (1) - buttonB (0) 을 할 생각 buttonA 클릭하지만, 다음과 같은 코드가

buttonA (1) - buttonB (-1) 

내가 원하는 것은 보여 주면

buttonA (0) - buttonB (0). 

이 될 것입니다 버튼 전에 클릭하면, 버튼 만있는 사용자 버튼을 감소하지 전에 그것을 클릭하십시오. 코드를 개선하려면 어떻게해야합니까? 지저분 해 보인다.

$this.addClass('active').siblings().removeClass('active'); 
if ($this.is('span[name="ans_yes"]')) { 
    yes_no = 1; 
    currentVal = parseInt($this.find('.badge').html()); 
    $this.find('.badge').html(currentVal + 1); 

    currentVal2 = parseInt($id.find('.ans-no').html()); 
    $id.find('.ans-no').html(currentVal2 - 1); 
} else { 
    yes_no = 0; 
    currentVal = parseInt($this.find('.badge').html()); 
    $this.find('.badge').html(currentVal + 1); 

    currentVal2 = parseInt($id.find('.ans-yes').html()); 
    console.log(currentVal2); 
    $id.find('.ans-yes').html(currentVal2 - 1); 
} 

업데이트 - demo

+1

해당 html로 jsfiddle.net에서 데모 만들기 – charlietfl

+0

@charlietfl 데모를 추가했습니다 – vzhen

+0

여러 개의 buttonA 및 buttonB가 페이지에 있습니까? 아니면 각각 하나만 있습니까? 값은 0 또는 1입니까? 우리는 당신이 실제로 가고있는 것을 알아 내기 위해 좀 더 자세한 내용을 사용할 수 있습니다. –

답변

1

HTML 구조를 꽤 비슷하게 유지하려고했지만 JS가 완전히 닫혔습니다. 어떤 CSS없이 나는 그들이 buttonA 및 buttonB의 여러 인스턴스와 http://jsfiddle.net/TtkDG/3/에서 근무 (만약 아무것도)

var answered = {}; 

$('.ans-yes-no').on('click', function(e) { 
    var questionId = $(this).parent().attr('id'); 
    var currentAnswer = answered[questionId]; 
    var count = parseInt($(this).children('.badge').html()); 

    if (currentAnswer == $(this).attr('name')) { 
     // Turning off 
     $(this).children('.badge').html(count-1); 
     delete answered[questionId]; 
    } else { 
     // If we have a different answer, turn that off 
     if (currentAnswer) { 
      var oldCountEl = $("#"+questionId).children("span[name="+currentAnswer+"]").children('.badge'); 
      var oldCount = parseInt(oldCountEl.html()); 
      oldCountEl.html(oldCount - 1); 
     } 

     // Turning on 
     $(this).children('.badge').html(count+1); 
     answered[questionId] = $(this).attr('name'); 
    } 
}); 

데모에 사용되는 있었는지 확실하지 않았다 때문에, 필요한 경우 active 클래스를 다시 장착해야합니다 .

편집 : 명확하게 말하면, 질문 ID가 포함 된 div에 단추를 래핑해야했습니다. 그냥 놓치지 않도록하십시오.

+0

나는 이것이 내가 원하는 것이라고 생각한다. – vzhen

+0

무엇을 알아낼 수 없기 때문에 다시 알 수 없으므로 var 응답 = {}; 대답했습니다 [topic_id];'평균 – vzhen

+0

자바 스크립트로 배열을 읽어야하는 것처럼 들립니다. http://blog.xkoder.com/2008/07/10/javascript-associative-arrays-demystified/을 확인하십시오. 길기는하지만 잘하면 도움이 될 것입니다. –

0
내가 처음에 거짓 변수 didtheuserclick을 사용하는 것이 좋습니다과 변수가 빼기보다 사실 여부를 확인 할

는 다른는 빼기 부분을 무시하고에 true로 변수를 설정 단지를 위해 그것을 사용하는 경우 클릭 기능의 끝, 나는 http://jsfiddle.net/TtkDG/1/

은 또한 당신이이 같은 논리의 각 클릭에 증가로 간단한 정수 변수를 사용하고 변수가 1과 동일 여부를 확인 할 수있는 데모를했지만 변수를 증가시키는 것은 의미가 없습니다. 특히 높은 숫자에 도달 할 것입니다.

도움이 되길 바랍니다.

+0

데모에 문제가 있습니다. 버튼 A를 다시 클릭하면 buttonB -1이 발생합니다. 앞에서 말했듯이, theuserdidclick before. – vzhen

0

나는 badge의 값을 토글 할 단일 함수를 만들었습니다. increment가 0보다 작 으면 0을 인쇄합니다. 또한주의

사용보다 요소에 다른 클래스를 추가하는 간단 name

$('.ans-yes-no').on('click', function (e) { 
     e.preventDefault(); 

     var $this = $(this), 
      $otherBtn = $this.siblings('.ans-yes-no'); 

     var $btnWrap = $this.closest('.topic-footer'); 
     /* check if user has already selected, test "active" class length*/ 
     var alreadyVoted = $btnWrap.find('.active').length; 
     if (alreadyVoted) { 
      if ($this.is('.active')) { 
       /* do nothing if already active?? */ 
       return; 
      } else { 
       $this.add($otherBtn).toggleClass('active'); 
      } 
     } else { 
      $this.addClass('active'); 
     } 

     toggleValue($this, 'up'); 
     toggleValue($otherBtn, 'down'); 
    }); 

    function toggleValue($element, direction) { 
     $element.find('.badge').text(function (i, currVal) { 
      var value = parseInt(currVal, 10); 
      direction == 'up' ? value++ : value--; 
      return value > -1 ? value : 0; 
     }) 
    } 

DEMO : http://jsfiddle.net/MZyxW/

그것은 어떤 행동이 계속 추가 할 수있는 사용자로까지 원하는 100 % 확실하지 않다 또는 사용자가 이미 대답을 clciked 경우 active 클래스로 html 각 페이지를로드합니다.