首页 > 解决方案 > 表格 - 隐藏一个元素,显示另一个

问题描述

我是 JavaScript 新手,我有一个问题。

我需要隐藏复选框,然后显示span内容“已取消”。

有人能帮助我吗?

$(document).ready(function() {
  // Find remove selected table rows
  $(".delete-row").click(function() {
    $('input[name="record"]').each(function() {
      if ($(this).is(":checked")) {
        if (confirm("Are you sure?")) {
          $(this).hide();
          $(this).closest('td').find('.canceled').show();
          console.log("confirmed");
        } else {
          console.log("canceled the deletion");
        }
      }
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tr>
  <td>First Name</td>
  <td>Last Name</td>
  <td>Address</td>
  <td>
    <input type="checkbox" name="record">
    <span class="canceled" style="visibility: hidden">Canceled</span>
  </td>
</tr>
<br />
<tr>
  <td>First Name 2</td>
  <td>Last Name 2 </td>
  <td>Address 2</td>
  <td>
    <input type="checkbox" name="record">
    <span class="canceled" style="visibility: hidden">Canceled</span>
  </td>
</tr>

<button type="button" class="btn btn-danger marginLeft20 delete-row">Cancel</button>

标签: javascriptjqueryhtml

解决方案


根据您提供的代码,当您取消第二个复选框时,警报会显示两次,这是因为第一个复选框已隐藏但未隐藏,unchecked并且each循环条件检查选中的复选框。因此,您可以取消选中复选框并隐藏它。

$(document).ready(function() {
  // Find remove selected table rows
  $(".delete-row").click(function() {
    $('input[name="record"]').each(function() {
      if ($(this).is(":checked")) {
        $(this).prop('checked', false);
        if (confirm("Are you sure?")) {
          $(this).hide();
          $(this).siblings('.canceled').css('visibility', 'visible');
          console.log("confirmed");
        } else {
          console.log("canceled the deletion");
        }
      }
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td>First Name</td>
    <td>Last Name</td>
    <td>Address</td>
    <td>
      <input type="checkbox" name="record">
      <span class="canceled" style="visibility: hidden">Canceled</span>
    </td>
  </tr>
  <br />
  <tr>
    <td>First Name 2</td>
    <td>Last Name 2 </td>
    <td>Address 2</td>
    <td>
      <input type="checkbox" name="record">
      <span class="canceled" style="visibility: hidden">Canceled</span>
    </td>
  </tr>
</table>
<button type="button" class="btn btn-danger marginLeft20 delete-row">Cancel</button>


推荐阅读