如何在table行显示数据?

How to display data in its row table?

假设我有 5 行数据,有没有办法可以在其行上显示数据?如何? 在我的代码中,当我点击第 5 行的按钮时,结果显示在数据列中。

<table>
<th>action</th><th>data</th>
<tr>
 <td>
   <button class="getdata" type="button" data-id="1">
 </td>
 <td>
   <i class="data"></i>
 </td>
</tr>
<tr>
 <td>
   <button class="getdata" type="button" data-id="2">
 </td>
 <td>
   <i class="data"></i>
 </td>
</tr>
<tr>
 <td>
   <button class="getdata" type="button" data-id="3">
 </td>
 <td>
   <i class="data"></i>
 </td>
</tr>....
</table>
$('.getdata').click(function(){
  var id = $(this).attr('data-id');
  $.ajax({
    url: 'log.php',
    method: 'GET',
    data:{id:id},
    success:function(){
      $('.data').html(id)
     }
    })
  })

在您的 AJAX 成功/完成处理程序中,从当前按钮向上遍历到合理的父级 (<tr>),然后向下遍历到 .data 元素

$('.getdata[data-id]').on("click", function() {
  const btn = $(this)
  $.get("log.php", { id: btn.data("id") }).done(data => {
    btn.closest("tr").find(".data").html(id) // or data ¯\_(ツ)_/¯
  })
})

.closest()


你知道吗,you might not need jQuery

// using event delegation at the <table> level
document.querySelector("table").addEventListener("click", async e => {
  const btn = e.target.closest("button.getdata[data-id]")
  if (btn) { // the click came from a button
    const id = btn.dataset.id
    const params = new URLSearchParams({ id })
    const res = await fetch(`log.php?${params}`)
    const data = await res.text()
    if (res.ok) {
      btn.closest("tr").querySelector(".data").innerHTML = id // or data
    } else {
      console.error(res.status, data})
    }
  }
})