Show/Hide 多个 <table> 带有复选框

Show/Hide more than one <table> with a checkbox

我想在一页上用一个按钮显示和隐藏多个 table。不幸的是,我的脚本一次只能显示和隐藏一个 table。

我有一个包含很多查询的页面。 table 中也有文本字段。为了更好地概览,带有文本字段的 table 只应在复选框被选中时显示。该复选框不应在开头单击。

function Displayer(n)
{
  var check = document.getElementById('Section'+n);
  if (check.style.display == 'none')
    {
      check.style.display='inline';
    }
    else
    {
      check.style.display='none';
    }
}
<p><input type="checkbox" class="btnstylega" onClick="Displayer(99)" />Show Tables</p>

<table id="Section99" style="display:none;"> <td>
AAAAAAAAAAAAAA
</td></table>

<table id="Section99" style="display:none;"> <td>
BBBBBBBBBBBBBBB
</td></table><br>

我想显示和隐藏许多 table,而不通过单击复选框调整 table。

ID 必须 在文档中是唯一的。将多个元素标记为组的一部分的工具是 class.

将您的 id 属性替换为 class 属性。

然后将getElementById替换为getElementsByClassName(或querySelectorAll)。

这些方法 return 节点列表而不是单个元素,因此 像数组一样遍历结果 并访问 style 属性 依次对每个。

属性id must be unique in a document, you can use class instead. You can use querySelectorAll() to target all the elements having the class, then loop through them to set the style. You can toggle the class using classList.toggle()如下所示:

function Displayer()
{
  var check = document.querySelectorAll('.Section99');
  check.forEach(function(table){
    table.classList.toggle('show');
  });
}
.Section99{
  display: none;
}
.show{
  display: block;
}
<p><input type="checkbox" class="btnstylega" onClick="Displayer()" />Show Tables</p>

<table class="Section99" class="hide"> <td>
AAAAAAAAAAAAAA
</td></table>

<table class="Section99" class="hide"> <td>
BBBBBBBBBBBBBBB
</td></table><br>

改进:它将添加事件处理程序并在需要时触发加载更改

注意复选框上的数据属性

var chg = new Event('change');
document.querySelectorAll(".btnstylega").forEach(function(but) {
  but.addEventListener("change", function() {
    var checked = this.checked,
      section = this.getAttribute("data-tables");
    document.querySelectorAll('.Section' + section).forEach(function(sect) {
      sect.classList.toggle("hide",!checked);
    });
  })
  but.dispatchEvent(chg);
});
.hide {
  display: none;
}
<p><input type="checkbox" class="btnstylega" data-tables="88" checked />Show Tables 88 </p>
<p><input type="checkbox" class="btnstylega" data-tables="99" />Show Tables 99</p>

<table class="Section88">
<tr>
  <td>
    AAAAAAAAAAAAAA
  </td>
  </tr>
</table>

<table class="Section88">
<tr>
  <td>
    BBBBBBBBBBBBBBB
  </td>
  </tr>
</table><hr>
<table class="Section99">
<tr>
  <td>
    CCCCCCCCCCCCCCCC
  </td>
  </tr>
</table>

<table class="Section99">
<tr>
  <td>
    DDDDDDDDDDDDDDDDDDDD
  </td>
  </tr>
</table>