首页 > 解决方案 > 如果表是使用 Thymeleaf 制作的,如何使用 jquery 获取表的第一个单元格的内容

问题描述

使用 Thymeleaf 动态创建的表。表格的每一行都附有一个 img 链接。单击我想获取所选行的 img 链接第一、第二和第三个单元格。

相关表格代码

<table class="table" id="tblDocType" style="padding: 20px 10px;">
<thead class="thead-dark">
<tr>
<th scope="col"> <b> Document Type </b></th>
<th scope="col"> <b> Practice Area </b> </th>
<th scope="col"><b> Retention Policy </b></th>
<th scope="col"> <b> Effective Date<br> Required </b></th>
<th scope="col"> <b> Termination Date<br> Required </b></th>
<th scope="col"> <b> Action</b></th>
</tr>
</thead>
<tr th:each="doctype,iterStat  : ${dlist}">
<td th:text = "${doctype?.doctypes}"></td>
<td th:text = "${doctype?.practiceAreaId}"></td>
<td th:text = "${doctype?.retention_policy}"></td>
<td th:text = "${doctype?.effectiveDateRequired}"></td>
<td th:text = "${doctype?.terminationDateRequired}"></td>
<td>
<a href="#" th:name="${doctype?.practiceAreaId}" th:id="${iterStat.index}" onclick="deleteTrigger(this.id)" style="color: blue;">
<span class="glyphicon glyphicon-trash"></span>
</a>
</td>
</tr>
</table>

我正在尝试使用 jquery 获取单元格值。

相关jquery代码

function deleteTrigger(id){
   var value=$("#tblDocType").closest("tr").find('td:eq(0)').text();
   console.log("value=",value);
   var doctypesjson={
          "doctypes": id,
          "practiceAreaId": pracaticeareaidfrombutton     
  };
}

在控制台中,该值变为空白。

如果您知道可以为这个问题做些什么,请帮助我。先感谢您

标签: javascriptjqueryhtmlthymeleaf

解决方案


目前,您的代码似乎正在寻找第一个 TR,然后是第一个TD。但是,这不会做任何事情,因为您的第一个 TR 仅包含TH

在调用你的 deleteTrigger() 函数时,你应该通过被点击的元素

deleteTrigger(this); // use this for your TR lookup. 

但是,由于您已经在使用 jQuery,完全放弃删除功能并使用侦听器可能会让您的生活更轻松;

$(“tr”).click(function(){
  $(this).find(“td”).first() // this will get the first td of a clicked row
  $(this).find(“td”).eq(1) // this will get second td etc...
})

推荐阅读