Javascript:在HTML中的数据属性中操作数据



我有一个html/js代码,从json中获取数据并将其呈现到html表。它已经工作了一段时间了。最近要处理的项目数量大大增加,无法再将数据静态地放入html中。所以我已经改变了html中的代码,我现在使用数据属性,和一个JS循环通过json文件中的每个项目,并将其写入html中正确的数据属性。它的工作原理。我有另一个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已经全部正确填充。事实上,除了上面的JS之外,所有的工作都很好。问题是:如何操作使用数据属性填充的数据?如果我用一个类来表示,结果是一样的。有提示吗?

更新:我发现,当数据被动态分配时,它会进入一个HTMLCollection,我现在可以读取,因为我发现使用哪个属性来选择正确的html元素。实际上,它包含了我需要的数据,并填充了td单元格。但是!不知道如何操作这个htmlcollection。我试过了,结果很奇怪。我已经了解到,在htmlcollection foreach不工作。使用array .from()将其转换为数组或使用for of循环。当我使用两者中的任何一个时,我将丢失数据并再次获得占位符{!最后引导!}。这是我得到的结果:

`
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显示数据不见了,尽管结构还在,我又回到了占位符。

解决。由于该表是由另一个JS脚本动态生成的,因此上面的JS代码将放置在该脚本(及其循环)中。

如果您有如下内容:

<div data-myAttribute="1"></div>
<div data-myAttribute="2"></div>
...

你选择他们:

const els = document.querySelectAll('div[data-myAttribute');
els.forEach(e => {
...
})

相关内容

最新更新