Edit:下面已经回答了这个问题。
我想要一个 HTML 表,其中每行之间都有隐藏行,其中包含有关顶级行的更多信息。单击第一列中的展开/折叠图像链接时,隐藏行的可见性将从 display:none; 切换。显示:表行;。我已经有一段时间没有编写 JavaScript 了,需要能够严格地在 JavaScript 中执行此操作,并且无法使用 jQuery toggle() 方法。
如何使用 JavaScript 查找按钮位于表内的 class="parentRow" 的同级行,然后切换该同级行的可见性?
HTML
<table style="width:50%">
<caption>Test Table</caption>
<thead>
<tr align="center">
<th><span class="offscreen">State Icon</span></th>
<th>Column 2</th>
<th>Column 3</th>
<th>Column 4</th>
<th>Column 5</th>
</tr>
</thead>
<tbody>
<tr align="center" class="parentRow">
<td><a href="#" onclick="toggleRow();"><img alt="Expand row" height="20px;" src="expand.png"></a></td>
<td>test cell</td>
<td>test cell</td>
<td>test cell</td>
<td>test cell</td>
</tr>
<tr style="display: none;" class="subRow">
<td colspan="5"><p>Lorem ipsum dolor sit amet...</p></td>
</tr>
....
</tbody>
</table>
CSS
.offscreen {
position: absolute;
left: -1000px;
top: 0px;
overflow:hidden;
width:0;
}
.subRow {
background-color: #CFCFCF;
}
JavaScript
function toggleRow() {
var rows = document.getElementsByClassName("parentRow").nextSibling;
rows.style.display = rows.style.display == "none" ? "table-row" : "none";
}
向您的事件处理程序传递对单击的行的引用this
:
<td><a href="#" onclick="toggleRow(this);"><img alt="Expand row" height="20px;" src="expand.png"></a></td>
然后更新您的toggleRow 函数,如下所示:
function toggleRow(e){
var subRow = e.parentNode.parentNode.nextElementSibling;
subRow.style.display = subRow.style.display === 'none' ? 'table-row' : 'none';
}
您可能需要考虑创建一个通用函数来向上导航 DOM 树(这样当您更改 HTML 时该函数就不会中断)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)