2016-12-22 1 views
1

타임 라인이있는 소셜 네트워크를 디자인 중이며 버튼이 있습니다. 나는 AJAX를 사용하여 서버 측에 같은 버튼을 적용한다. 문제는 그들이 성공적으로 좋아하는 즉시 각 게시물에 대한 like of의 수를 변경하고 싶다는 것입니다. 내 요소가 for-each에 의해 생성되기 때문에 정확한 요소의 수를 변경하고 싶습니다. 실제로 문제가 있습니다. 저는 thymeleaf를 사용하고 있습니다.변수 id로 요소 텍스트 변경

나는 이것을하는 방법을 찾고있다. 여기

내 HTML 코드입니다 :

<div class="col-sm-4"> 
    <div class="row" > 
     <div class="col-sm-12"> 
     <img th:if="${tweet.isFavorited()}" src="../static/images/like.png" th:src="@{/images/like.png}" th:class="like-img" th:id="${tweet.getId()}" width="35" height="35"/> 
     <img th:if="${!tweet.isFavorited()}" src="../static/images/dislike.png" th:src="@{/images/dislike.png}" th:class="like-img" th:id="${tweet.getId()}" width="35" height="35"/> 
    </div> 
</div> 
<div class="row"> 
    <div class="col-sm-12" > 
    <h6 th:if="${tweet.isRetweet()}" th:class="like-count" th:id="${tweet.getId()}" th:text="${tweet.getRetweetedStatus().getFavoriteCount()}"></h6> 
    <h6 th:if="${!tweet.isRetweet()}" th:class="like-count" th:id="${tweet.getId()}" th:text="${tweet.getFavoriteCount()}"></h6> 
    </div> 
</div> 

및 내 스크립트 코드입니다 : 당신이 고유 ID를 할당해야합니다이 일을 너무 좋아

$(function() { 
    $(".like-img").click(function() {  
    event.preventDefault(); 

    var $post = $(this); 
    var toSend = { 
     "tweetId": this.getAttribute("id") 
    } 

    $.ajax({ 
     type : "POST", 
     contentType: "application/json; charset=utf-8", 
     url : "like", 
     data : JSON.stringify(toSend), 
     dataType : 'json' 
    }).done(function (data) { 
     if(data.status == "success") { 
      if ($($post).attr("src") == "/images/dislike.png") { 
       $($post).attr('src','/images/like.png'); 
      } 
      else { 
       $($post).attr('src','/images/dislike.png'); 
      } 

      return false; 
     } 
    });   
    });   
}) 

답변

0

like-count 요소는 다음과 같습니다.

<h6 th:if="${tweet.isRetweet()}" th:class="like-count" th:id="${tweet.getId()}_like_count" th:text="${tweet.getRetweetedStatus().getFavoriteCount()}"></h6> 

그러면 현재 카운트를 가져 와서 증분하고 카운트 요소의 텍스트를 설정할 수 있습니다. 다음과 같은 것 :

var currentCount = parseInt($('#'+toSend.tweetId+'_like_count').innerHtml) 
var newCount = currentCount++; 
$('#'+toSend.tweetId+'_like_count').text(newCount); 
+0

실제로 $ ('#'+ toSend.tweetId + '_ like_count'). innerHtml은 undifiend를 반환합니다! –

+0

.innerHtml 대신 .text()를 사용하십시오. 텍스트 사용을 설정하려면 element.text ('new text'); –