[Django] JavaScript로 새로고침 없이 좋아요, 싫어요 개수 올리기

JH Park·2021년 6월 16일
0

Web

목록 보기
4/7
post-thumbnail
<script>
  function count(type, num) 
  {
  	var resultElement = document.getElementById(type + num);
  	var number = resultElement.innerText;
  	number = parseInt(number) + 1;
 	resultElement.innerText = number;
  }
</script>
<div id="like">
  <a href="{%url 'yesUp' text.place content.id%}">
  	<input type="button" id="yes" onclick='count("yes","{{ forloop.counter }}")' value="좋아요" />
  </a>
  <div id="yes{{forloop.counter}}" name="yes">
  {{content.yes}}
  </div>
</div>
<div id="hate">
  <a href="{%url 'noUp' text.place content.id%}">
  <input type="button" id="no" onclick='count("no","{{ forloop.counter }}")' value="싫어요" />
  </a>
  <div id="no{{ forloop.counter }}" name="no">
  {{content.no}}
</div>

count(type,num)에서
type: yes 또는 no를 넘겨 받기
num: for문 내에서 content가 몇번째 원소인지

굳이 num을 넘겨 받아야될까 싶었지만 for 문을 돌렸을 때 첫번째 yes button의 id만 yes기 때문에 무슨 버튼을 눌러도 첫번째 yes만 숫자가 올라갔다.

이를 방지하기 위해 각 버튼 id="yes"(혹은 "no")+for문 내 몇번째인지로 설정하였다.
{{forloop.counter}}를 사용하여 for문 내 몇번째인지를 알 수 있다.

type을 넘겨 받은 이유는 yes와 no function을 따로 만들지 않고 하나의 function으로 처리하기 위해서다.

profile
Computer Engineering Student

0개의 댓글