javascript - 需要在html中的列的每个单元格中添加复制按钮
问题描述
我正在尝试在我的角度应用程序中使用 ngx-clipboard 模块。
表中的数据来自服务,我jsonToTable()
用来插入动态表。
组件.ts
generateOverrideCode(){
try {
document.getElementById('tableGoesHere').innerHTML = this.jsonToTable(data, 'table table-sm table-dark');
}
catch (ex) {
console.log('--generate override code', ex);
}
}
capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
jsonToTable(json, classes){
var cols = Object.keys(json[0]);
var headerRow = '';
var bodyRows = '';
classes = classes || '';
cols.map((col)=>{
headerRow += '<th>' + this.capitalizeFirstLetter(col) + '</th>';
});
json.map((row)=> {
bodyRows += '<tr>';
cols.map((colName)=> {
if(colName != 'population')
bodyRows += '<td>' + row[colName] + '</td>';
else
bodyRows += '<td id="colName+row">' + row[colName] + '<button></button>' + '</td>'; //I want to add a dynamic id to the button added to each cell of this row, so that i can use the id to target the text of that cell.
});
bodyRows += '</tr>';
});
return '<table class="' +
classes +
'"><thead><tr>' +
headerRow +
'</tr></thead><tbody>' +
bodyRows +
'</tbody></table>';
}
}
var data = [
{ country: 'China', population: 1379510000 },
{ country: 'India', population: 1330780000 },
{ country: 'United States', population: 324788000 },
{ country: 'Indonesia', population: 260581000 },
{ country: 'Brazil', population: 206855000 },
];
组件.html
<div class="row">
<div class="col-sm-12">
<button (click)="generateOverrideCode()">Generate</button>
</div>
</div>
<div id="tableGoesHere"></div>
我还希望每个单元格都有一个唯一的 id,这样我就可以使用 ngx-clipboard 指令来定位它。以链接为例
https://maxisam.github.io/ngx-clipboard/
我也创建了一个 stackblitz 示例。 https://stackblitz.com/edit/angular-s5g1b5
请帮助我为每个单元格添加唯一 ID,然后我将继续添加 ngx-clipboard。(我在 stackblitz 中添加了评论,我尝试添加唯一 ID)
解决方案
推荐阅读
- android - 更改 RecyclerView 项目的宽度会使视图消失
- c++ - 问题更改选项卡 QTabWidget & QScrollArea Qt
- spring-boot - 架构领域模型和视图模型
- javascript - 显示/隐藏图像取决于日期
- java - HexBinary字节顺序
- javascript - JQuery datatablejs土耳其字符搜索问题
- sql - 使用左连接 SQL Server 时如何提高搜索速度?
- android - 为什么 button.ispressed() 不适用于 android 的东西
- javascript - (修改 JSFiddle)如何根据上一个下拉列表中选择的内容制作附加级别下拉列表?
- javascript - 有没有办法按照 CloudFormation 模板中指定的顺序获取 ProvisioningArtifactParameters?