2016-12-22 8 views
1

私はタイムラインを持つソーシャルネットワークを設計しており、ボタンのようなものがあります。私はAJAXを使用して、サーバー側に同様のボタンを適用します。問題は、成功した直後に各投稿の数を変更したいということです。私の要素は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> 

、それは私のスクリプトコードです:

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

わかりましたので、あなたに固有のIDを割り当てる必要があります。この仕事をするために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'); –

関連する問題