【发布时间】:2019-01-16 02:38:16
【问题描述】:
我试图在 div 中显示一个隐藏的表格,然后使用 display: none/block 切换再次隐藏它。有用。但是,一旦我切换到 display: none 来隐藏它,我就无法让它再次出现。
HTML: HTML 有一个 id = tableContainer 的空 div。
在它旁边,我有一个表格,上面有每个单元格中动物科的名称,还有一个按钮。单击该按钮时,它会从该特定单元格中获取动物家族的名称,找到具有该名称的动物物种表,然后从 display: none 切换到 display:block 并在 div 内显示它。然后,如果我再次单击该按钮,它会将显示切换回显示:无。
当我单击另一个单元格中的按钮时,它会清除 div 并显示新表格。
一切都好。
但是,如果我单击以前使用的按钮,则现在已消失的表不再可用。
我在 removeChild 和所有这些方面都经历了各种各样的麻烦,但没有运气。我目前正在使用 innerHTML 来清除 div,但我缺少类名的内容。
控制台错误说:tabletest2.html:523 Uncaught TypeError: Cannot read property 'classList' of null 在切换 (tabletest2.html:523) 在 HTMLButtonElement.onclick (tabletest2.html:72)
所以,在我看来,它不能再切换了,因为表现在不再存在,或者我可能错了,因为我没有删除子元素(我认为)。
<body>
<table>
<tbody>
<tr>
<td>Genus</td>
<td>Benthobatis
<button onclick="toggle(this, parentNode.firstChild)">Click me</button></td>
</tr>
<tr>
<td>Genus</td>
<td>Diplobatis
<button onclick="toggle(this, parentNode.firstChild)">Click me</button></td>
</tr>
</tbody>
</table>
<!-- <======== div display container here ================>-->
<div id="tableContainer"></div>
<table id="Benthobatis" class="hide">
<tbody>
<tr>
<th>Genus</th>
<th>Benthobatis</th>
</tr>
<tr>
<td>Benthobatis kreffti</td>
<td>Brazilian Blind Electric Ray</td>
</tr>
</tbody>
</table>
<!-- <==================================-->
<table id="Diplobatis" class="hide">
<tbody>
<tr>
<th>Genus</th>
<th> Diplobatis </th>
</tr>
<tr>
<td>Diplobatis colombiensis</td>
<td>Colombian electric ray</td>
</tr>
</tbody>
</table>
</body>
<script>
function toggle(ele, tableName) {
var myTableDisplayDiv = document.getElementById("tableContainer").childNodes;
if (myTableDisplayDiv.length != 0) {
document.getElementById("tableContainer").innerHTML = "";
}
var myTableName = tableName.textContent;
var myTable = document.getElementById(myTableName);
myTable.classList.toggle("hide");
document.getElementById("tableContainer").appendChild(
document.getElementById(myTableName)
);
}
</script>
<style>
.hide {
display: none;
}
【问题讨论】:
-
#tableContainer是哪个元素?我假设比<table>高一级? -
tableContainer 是我放置表格的空 div。所以它是 html:body:tableContainer。这些表都与 tableContainer 处于同一级别/层次结构,但在按钮单击时切换到 div。
标签: javascript