1 回答
TA贡献1818条经验 获得超7个赞
您的代码中有几个问题:
.slice(1, );
- 我认为这是一个语法错误。应该是.slice(1);
(没有逗号).
选择器缺少类名的点- 因此更改此行以包含它,如下所示:var toggle_class_name = '.child-of-${category_id}';
最好使用所需的属性切换类,而不是手动添加删除属性
请参阅下面的工作演示:
document.addEventListener('DOMContentLoaded', function() {
document.querySelectorAll('.cat').forEach(category => {
category_id = category.getAttribute('id').slice(1);
var toggle_class_name = `.child-of-${category_id}`;
category.addEventListener('click', () => toggle_class(toggle_class_name));
});
});
function toggle_class(toggle_class_name) {
console.log(toggle_class_name);
document.querySelectorAll(toggle_class_name).forEach(item => {
item.classList.toggle('hidden');
});
};
tr.hidden{
display: none;
}
<div>
<table class='table' border=1>
<tr>
<th class='ref-col'>Reference</th>
<th class='des-col'>Description</th>
<th class='mth-head'>Jun-20</th>
<th class='mth-head'>Jul-20</th>
<th class='mth-head'>Aug-20</th>
</tr>
<tr id='c2' class='child-of-None cat'>
<td class='ref-col'>C0002</td>
<td class='des-col'>Financial Statements</td>
<td class='amt-col'></td>
<td class='amt-col'></td>
<td class='amt-col'></td>
</tr>
<tr id='c1' class='child-of-2 cat'>
<td class='ref-col'>C0001</td>
<td class='des-col'>   Balance Sheet</td>
<td class='amt-col'></td>
<td class='amt-col'></td>
<td class='amt-col'></td>
</tr>
<tr id='c6' class='child-of-1 cat'>
<td class='ref-col'>C0006</td>
<td class='des-col'>      Non-Current Assets</td>
<td class='amt-col'></td>
<td class='amt-col'></td>
<td class='amt-col'></td>
</tr>
<tr id='c11' class='child-of-6 cat'>
<td class='ref-col'>C0011</td>
<td class='des-col'>         Property, Plant & Equipment</td>
<td class='amt-col'></td>
<td class='amt-col'></td>
<td class='amt-col'></td>
</tr>
<tr id='g1000001' class='child-of-11 gl'>
<td class='ref-col'>1000001</td>
<td class='des-col'>            Freehold Land</td>
<td class='amt-col'></td>
<td class='amt-col'></td>
<td class='amt-col'></td>
</tr>
</table>
</div>
添加回答
举报