gpt4 book ai didi

javascript - 如何覆盖表中的数据?

转载 作者:行者123 更新时间:2023-11-28 14:17:51 24 4
gpt4 key购买 nike

单击链接时尝试创建具有数据属性的表格

问题很可能出在这段代码中

我不明白如何重写表中的数据。现在数据已按顺序添加到表中。

我的代码 - https://jsfiddle.net/347x8bwq/

(function() {

'use strict';

function createTable() {
let link = document.querySelectorAll('.link');
let block = document.querySelector('.block');
let blockTable = document.querySelector('.table');

for (let i = 0; i < link.length; i++) {

let links = link[i];

links.addEventListener('click', function(e) {
e.preventDefault();

let linkData = this.dataset;

for (let j in linkData) {
let tableRow = document.createElement('tr');

let arr = linkData[j].split('|');
for (let k = 0; k < arr.length; k++) {
let tableCol = document.createElement('td');
tableCol.innerHTML = arr[k];
tableRow.appendChild(tableCol);

}

blockTable.appendChild(tableRow);

}


});
}
}
createTable();

期望的行为 - 每次单击链接时 - 创建一个新表

最佳答案

在将 tableRow 附加到 blockTable 之前,请清除其 innerHTML

(function() {

'use strict';

function createTable() {
let link = document.querySelectorAll('.link');
let block = document.querySelector('.block');
let blockTable = document.querySelector('.table');

for (let i = 0; i < link.length; i++) {

let links = link[i];

links.addEventListener('click', function(e) {
e.preventDefault();

let linkData = this.dataset;
blockTable.innerHTML = "";


for (let j in linkData) {
let tableRow = document.createElement('tr');

let arr = linkData[j].split('|');
for (let k = 0; k < arr.length; k++) {
let tableCol = document.createElement('td');
tableCol.innerHTML = arr[k];
tableRow.appendChild(tableCol);
}
blockTable.appendChild(tableRow);

}

});
}
}
createTable();



})();
.table {
width: 100%;
table-layout: fixed;
}

td {
border: 1px solid #ccc;
}

.link {
display: block;
margin-bottom: 5px;
}

.block {
padding: 25px;
border: 1px solid #000;
}
<a href="#" class="link" data-title="Атрибут1|Title" data-subtitle="Атрибут2|Subtitle" data-num="Атрибут3|1234">Link 1</a>

<a href="#" class="link" data-text="Атрибут1|Title" data-online="Атрибут2|off">Link 2</a>

<a href="#" class="link" data-text="Атрибут55|Title text" data-online="Атрибут02|Bubu">Link 3</a>


<div class="block">
<table class="table">
<tr>
<td>Атрибут1</td>
<td>Title</td>
</tr>
<tr>
<td>Атрибут2</td>
<td>Subtitle</td>
</tr>
<tr>
<td>Атрибут3</td>
<td>1234</td>
</tr>
</table>
</div>

参见 - https://jsfiddle.net/2wvm6de8/

关于javascript - 如何覆盖表中的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56650215/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com