【问题标题】:I am trying to send id to Controller with a dynamic button but it is not working我正在尝试使用动态按钮将 id 发送到控制器,但它不起作用
【发布时间】:2022-01-16 18:23:14
【问题描述】:

我正在尝试使用按钮将对象的 id 发送到控制器。但它只对列表第一行中的项目执行此操作。该按钮不适用于列表中的其他项目。我该如何解决这个问题?

$(document).ready(function () {
  $("#showTweet").click(function () {
    var tweetId = $(this).parent().attr("id");
    $.ajax({
      type: "GET",
      dataType: "json",
      url: "http://localhost:8020/showTweet?tweetId=" + tweetId,
      success: function (result) {
        var description = result.description;
        $("#tweetText").text(description);
      },
    });
  });
});

    
<table id="myTable" class="table table-striped">
  <thead>
    <tr>
      <th>Kullanıcı</th>
      <th>Oluşturulma Tarihi</th>
      <th>Seçenekler</th>
    </tr>
  </thead>
  <tbody>
    <tr th:each="unapprovedTweets: ${unapprovedTweets}">
      <td th:text="${unapprovedTweets.creative}"></td>
      <td th:text="${unapprovedTweets.create_date}"></td>
      <td>
        <div th:id="${unapprovedTweets.id}" style="width: 0px; height: 0px; display: contents;">
          <a id="showTweet" class="btn btn-warning">Tweeti Gör</a>
        </div> <a th:href="@{'/sendTweet/' + ${unapprovedTweets.id}}" class="btn btn-primary" style="width: 90px; margin-left: 5px;">Onayla</a>
        <a th:href="@{'/refuseTweet/' + ${unapprovedTweets.id}}" class="btn btn-danger" style="width: 90px; margin-left: 5px;">Reddet</a>
      </td>
    </tr>
  </tbody>
  </table>

【问题讨论】:

  • ids 在文档中是唯一的,jQuery 仅找到 id 为 showTweet 的单个元素,并且仅将偶数附加到该元素。使用 class 属性来识别更大的元素组。也可以并强烈建议在表格元素上使用event delegation

标签: javascript ajax spring-boot thymeleaf


【解决方案1】:

您可以通过th:attr 使用data-... 属性来跟踪id:

替换:

<div th:id="${unapprovedTweets.id}"
     style="width: 0px; height: 0px; display: contents;">

与:

<div th:attr="data-tweetId=${unapprovedTweets.id}" 
     style="width: 0px; height: 0px; display: contents;">

在您的 JavaScript 中,使用:

$(document).ready(function(){       
            $("#showTweet").click(function(){
         var tweetId = $(this).parent().attr('data-tweetId');
        $.ajax({
        
        type: "GET",
        dataType: "json",
        url: "http://localhost:8020/showTweet?tweetId="+tweetId,
        success: function(result){
            var description = result.description;
            $('#tweetText').text(description);
            
             }
        });
    });

【讨论】:

  • 据我了解,问题是在列表的其他元素中检测到具有相同名称的按钮。谢谢你的建议。你对多按钮点击有什么建议吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-11-22
  • 1970-01-01
  • 1970-01-01
  • 2020-04-30
  • 1970-01-01
  • 2020-11-17
  • 1970-01-01
相关资源
最近更新 更多