javascript - 使用变量 id 更改元素的文本

标签 javascript html ajax thymeleaf

我正在设计一个有时间线和喜欢按钮的社交网络。我使用 AJAX 在服务器端应用“点赞”按钮。问题是我想在每个帖子成功喜欢后立即更改喜欢的数量。因为我的元素是由 for-each 生成的,所以我想更改确切元素的 like 数量,我确实有问题。我正在使用 thymeleaf。

我正在寻找如何做到这一点的想法。

这是我的 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;
        }
    });        
  });        
})

最佳答案

好的,为了完成这项工作,您需要为点赞计数元素分配唯一的 id,如下所示:

<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);

关于javascript - 使用变量 id 更改元素的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41290530/

相关文章:

javascript - 为 block 元素的宽度设置动画,因为它随 jQuery 的变化而变化?

javascript - $watch 没有被解雇

javascript - 如何使用 AJAX 访问 Recurly API?

html - ul 和 li 中 anchor 悬停的 CSS

html - 具有侧div高度的可滚动div

javascript - 更改纵向屏幕的 CSS(例如 iPad)

html - 难以让社交媒体图标内联显示

javascript - 在更改事件上加载 jQuery DataTable

javascript - AJAX PHP 图像上传无法正常工作,$_FILES 为空?

php - 如何在 AJAX 修改元素的 html 后执行 jQuery 函数?