首页 > 解决方案 > 如何在表中设置为默认值?

问题描述

我有一个 Html 表,其中每一行都有一个按钮。当我单击一个按钮时,它会再显示 2 个按钮,然后就消失了。当我单击其他行的按钮时,我试图隐藏显示的按钮,但我不知道该怎么做。

这是我的功能代码

$("#myTable").on('click', 'tbody tr #editAction', function (e) {    
  $(this).hide().closest("tr").find("#deleteAction").show();
  $(this).hide().closest("tr").find("#saveAction").show();
});

标签: javascripthtml

解决方案


您应该将 id 更改为 class,如果您使用 id,则只有第一行将应用事件。将您的代码更改为

 $(".editAction").click(function (e) {    
     $("tr").find(".deleteAction").hide();
     $("tr").find(".saveAction").hide();
     $("tr").find(".editAction").show();
      //show delete and save
     $(this).closest("tr").find(".deleteAction").show();
     $(this).closest("tr").find(".saveAction").show();
     //hide edit button
     $(this).hide();
});

$(".editAction").click(function (e) {    
 $("tr").find(".deleteAction").hide();
 $("tr").find(".saveAction").hide();
 $("tr").find(".editAction").show();
  //show delete and save
  $(this).closest("tr").find(".deleteAction").show();
  $(this).closest("tr").find(".saveAction").show();
  //hide edit button
  $(this).hide();
});
.deleteAction, .saveAction{
display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<style>
table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td, th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
}

tr:nth-child(even) {
  background-color: #dddddd;
}
</style>
</head>
<body>

<table>
  <tr>
    <th>Company</th>
    <th>Contact</th>
    <th>Edit</th>
    <th></th>
    <th></th>
  </tr>
  <tr>
    <td>Alfreds Futterkiste</td>
    <td>Maria Anders</td>
    <td>
    <button class='editAction'>Edit</button>
    </td>
    <td>
    <button class='deleteAction'>Delete</button>
    </td>
    <td>
    <button class='saveAction'>Save</button>
    </td>
  </tr>

  <tr>
    <td>Ernst Handel</td>
    <td>Roland Mendel</td>
       <td>
    <button class='editAction'>Edit</button>
    </td>
    <td>
    <button class='deleteAction'>Delete</button>
    </td>
    <td>
    <button class='saveAction'>Save</button>
    </td>
  </tr>
 
</table>

</body>
</html>


推荐阅读