【问题标题】:How to hide values in a table Row and show it when you click on plus如何隐藏表格行中的值并在单击加号时显示它
【发布时间】:2019-12-14 01:30:21
【问题描述】:

我试图隐藏我的一列的表值,因为它有超过 10 个值,并且仅在您单击加号时显示它。否则,当您单击减号时,它会隐藏列值

我的尝试如下。它有效,但不是我想要的方式。当您单击加号时,它只显示第一个值而不是其余值。 我对 JS 了解不多,谁能给我更多关于如何处理这个问题的线索?

这是我的代码

HTML

<table>
  <thead>
         <tr>
            <th>Forms</th>
         </tr>
     </thead>
     <tbody>

        <tr>
         <td id="details-control" class="details-open">

   <span id='content' class="d-none"><?= $row->getElement()?><br> </span>
  </td>

            </tr>
        </tbody>

CSS

td.details-open {
    background: url("../img/details_open.png") no-repeat center center;
    cursor: pointer;
}
td.details-close {
    background: url("../img/details_close.png") no-repeat center center;
}

我的脚本

    $(document).ready(function(){
    $('#details-control').on('click', function (e) {
        $("#content").removeClass("d-none")
        $("#details-control").removeClass("details-open")
        $("#details-control").addClass("details-close")

    });
});

【问题讨论】:

  • 把你的 html 放在这里,因为 php 代码在这里不起作用。
  • html 已发布。这是我要操作的表格数据
  • 打印表格和打印的html粘贴到这里。

标签: javascript php jquery datatable datatables


【解决方案1】:

这个问题有两个原因。首先,当它们在 DOM 中必须是唯一的时,您在多个地方重复相同的 id。如果您想按共同目的或行为对元素进行分组,请将它们更改为类。

其次,您尝试在单击单元格时选择所有 #content 和 #details-control 元素。您需要改为使用 DOM 遍历来查找与单击的单元格相关的内容。为此,请使用 this 关键字。

话虽如此,请尝试以下示例。请注意,添加颜色只是为了使效果更明显,因为图像 URL 在此站点上不起作用。

$(document).ready(function() {
  $('.details-control').on('click', function(e) {
    var $cell = $(this).toggleClass('details-open details-closed');
    $cell.find('.content').toggleClass('d-none');
  });
});
td.details-open {
  background: url("../img/details_open.png") no-repeat center center;
  cursor: pointer;
  color: #C00;
}

td.details-close {
  background: url("../img/details_close.png") no-repeat center center;
  color: #CCC;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <th>ID</th>
      <th>Forms</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>
        Key #1
      </td>
      <td class="details-control details-open">
        <span class="content d-none">Name #1<br> </span>
        <span class="content d-none">Name #2<br> </span>
      </td>
    </tr>
    <tr>
      <td>
        Key #2
      </td>
      <td class="details-control details-open">
        <span class="content d-none">Name #3<br> </span>
        <span class="content d-none">Name #4<br> </span>
        <span class="content d-none">Name #5<br> </span>
      </td>
    </tr>
  </tbody>
</table>

【讨论】:

  • 哦,我明白了,现在我明白我的错误是什么了。非常感谢您的详细解释。使用类而不是 id 将元素组合在一起很有意义
  • 我可以问一个与此相关的快速问题吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-06
  • 2018-07-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多