【问题标题】:Show or hide table column of dynamically added rows显示或隐藏动态添加行的表格列
【发布时间】:2011-09-15 15:45:18
【问题描述】:

我有一个表,其中包含一些隐藏列,当用户单击按钮时需要显示这些列。然后,当单击页面上的其他位置时,该表格将被提供其他数据。所以基本上我有一个可以稍后填充的表。

我已经设法使用 jQuery 的切换来完成这项工作,但问题是新添加的行将保留原始 css 属性,被隐藏。

<style>
.hidden { display: none;}
</style>
<table>
<tr>
<th>test</th>
<th class="hidden">you cannot see me</th>
</tr>
<tr>
<td>test</td>
<td class="hidden">you cannot see me</td>
</tr>
</table>
<button onclick="$('.hidden').toggle()">
<button onclick="addrow ()">

请原谅任何拼写错误或语法错误。

第一次单击按钮时,隐藏的列会显示出来。

如果我然后单击 addrow,则新添加的行将显示 ORIGINAL display:none,因此我将第 1 行展开,第 2 行隐藏。

如何让新行处于最后的显示状态?

【问题讨论】:

  • 你能告诉我们addrow()函数的代码吗?另外,为了可读性/可维护性,我会放弃该内联 JS。
  • 为什么不直接使用 jQuery 来获取上一行的 .hidden 单元格的可见性?

标签: javascript jquery html


【解决方案1】:

我已经删除了内联 JS。

我为切换按钮添加了一个数据属性(也可以通过检查已放置的单元格来完成,但我认为如果您想添加其他功能会更好)。

HTML

<style>
.hidden { display: none;}
</style>
<table>
<tr>
<th>test</th>
<th class="hidden">you cannot see me</th>
</tr>
<tr>
<td>test</td>
<td class="hidden">you cannot see me</td>
</tr>
</table>
<button class="toggle" data-state="off">
<button class="add-row">

JS

$('document').ready(function() {
  $('.toggle').click(function() {
    if ($(this).data('state') == 'off') {
      $(this).data('state', 'on')
    } else {
      $(this).data('state', 'off')
    }
    $('.hidden').toggle();
  });

  $('add-row').click(function() {
    // code that adds the row

    if ($('.toggle').data('state') == 'on') {
      $('.hidden').show();
    }
  });
});

【讨论】:

  • 这是一个很好的解决方案,但我希望添加已经可见或不可见的行,以避免给用户造成混淆,或者隐藏或不显示的行。
【解决方案2】:

我通过在生成新行的 php 代码中添加检查来解决。 在新行单击时,如果线条应隐藏或显示,我将传递给帖子。在后一种情况下,我添加了一个 style="display:table-row;"到 .hidden 单元格,因此它们已经在表格上可见。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-13
    • 1970-01-01
    • 2011-09-05
    • 2015-01-04
    相关资源
    最近更新 更多