【发布时间】:2022-12-10 03:43:18
【问题描述】:
我有一个 html/js 代码,它从 json 中获取数据并将其呈现为 html 表。它已经工作了一段时间了。最近处理的项目数量大大增加,不能再将数据静态地放入html中了。所以我更改了 html 中的代码,现在我正在使用数据属性,以及一个循环遍历 json 文件中的每个项目并将其写入 html 中正确数据属性的 JS。有用。 我有另一个 JS 文件扫描所有 td 单元格,如果满足条件,单元格中的文本将变为红色或紫色。否则它仍然是标准的黑色。这曾经有用,但现在不行了。
这是实现的新 html 代码:
`
<table id="table" align="center" render-area="reboot">
<thead>
<tr>
<th class="text-center" data-tsorter="input-text">
Server Name
<img src='/icons/sort.png' width='20' height='20' style='display:inline;'>
</th>
<th class="text-center" data-tsorter="numeric">
Last Boot
<img src='/icons/sort.png' width='20' height='20' style='display:inline;'>
</th>
</tr>
</thead>
<tbody render-action="loop">
<tr render-data="json">
<td>{!Server Name!}</td>
<td>{!Last Boot!}</td>
</tr>
</tbody>
</table>
` 下面是不再工作的 JS:
`
const today = new Date();
const todayMonth = (today.getMonth())+1;
const todayDay = today.getDate();
// Query all table cells in document
document.querySelectorAll('table td').forEach(function(td) {
const srvDay = parseInt(td.innerHTML.split('/')[1]); // day
if(Number.isInteger(srvDay)){
const srvMonth = parseInt(td.innerHTML.split('/')[0]); //month
// If date contained in td text before current date then apply red background style
if(srvDay != todayDay || srvMonth != todayMonth){
td.style.color = "red";
}
}
if((td.innerHTML.split(' ')[0]).includes('unreachable')){
td.style.color = "purple";
}
});
` 如果我通过控制台检查该表 td,我会发现 td html 是 !Last Boot!这就是为什么我相信上面的 JS 不再工作了。但是,如果我查看 Elements 控制台,我会发现 DOM 已正确填充所有 td。事实上一切正常,除了上面的 JS。问题是:如何操作使用数据属性填充的数据?如果我为那个 td 使用一个类,我会得到相同的结果。有什么提示吗?
更新:我发现当数据被动态分配时,它会进入一个 HTMLCollection,我现在可以读取它,因为我发现了使用哪个属性来选择正确的 html 元素。事实上,它包含我需要的数据,并填充了 td 单元格。 但!不知道如何操作这个 htmlcollection。我试过了,结果很奇怪。我了解到在 htmlcollection foreach 上不起作用。使用 Array.from() 将其转换为数组或使用 for of 循环。当我使用两者中的任何一个时,我会丢失数据并再次获得占位符 {!Last Boot!}。这是我走了多远:
`
function tdTextHandler(renderArea){
const today = new Date();
const todayMonth = (today.getMonth())+1;
const todayDay = today.getDate();
const newArr = document.querySelectorAll(`[render-area="${renderArea}"]`);
newArr.forEach(function(e) {
const newArr4 = (Array.from(e.children))[1].children
console.log(newArr4);
for (item of newArr4) {
console.log(item);
const srvDay = parseInt(item.innerHTML.split('/')[1]); // day
if(Number.isInteger(srvDay)){
const srvMonth = parseInt(item.innerHTML.split('/')[0]); //month
// If date contained in td text before current date then apply red background style
if(srvDay != todayDay || srvMonth != todayMonth){
item.style.color = "red";
}
}
if((item.innerHTML.split(' ')[0]).includes('unreachable')){
item.style.color = "purple";
}
};
`
第一个 console.log 告诉我我有一个 htmlcollection,在控制台中我可以看到它的条目有数据。但是第二个 console.log 显示数据不见了,尽管结构在那里,我又回到了占位符。
【问题讨论】:
标签: javascript html json custom-data-attribute