[英]How to edit the HTML inside a table using JavaScript
当我尝试在html表格上添加按钮时,表格将不会出现。 在“ ligne”的最后一个元素上td class=ach
。
function afficherCatalogue(livres){ var ligne; for(var i in livres) { ligne = '<tr>'; ligne += '<td class=ref>' + Object.keys(livres[i])[0] + '</td>'; ligne += '<td class=aut>' + livres[i].auteur + '</td>'; ligne += '<td class=tit>' + livres[i].titre + '</td>'; ligne += '<td class=prx>' + livres[i].prix + '</td>'; ligne += '<td class=ach>' + <button type="button"></button> + '</td>'; ligne += '</tr>'; document.getElementById('tbc').innerHTML += ligne; }
<tbody id=tbc><!-- table to fill --></tbody>
我必须添加一个简单的按钮。
假设livres
引用了一个对象数组,则需要从表中删除tbody
并使用JavaScript使用createElement()
方法创建tbody
元素。
创建元素之后,可以使用for循环从数组中的每个对象检索所需的数据,并将其分配给ligne
变量。
通过对象循环后,可以再填充tbody
你只是从获取的数据创建的元素ligne
变量使用的innerHTML()属性,然后追加tbody
元素来使用你的表的appendChild()这样的方法:
/* JavaScript */ var table = document.getElementById("table"); function afficherCatalogue(livres){ var ligne = ""; var tbody = document.createElement('tbody'); tbody.setAttribute("id", "tbc"); for(i = 0; i < livres.length; i++) { ligne = '<tr>'; ligne += '<td class=ref>' + Object.keys(livres[i])[0] + '</td>'; ligne += '<td class=aut>' + livres[i].auteur + '</td>'; ligne += '<td class=tit>' + livres[i].titre + '</td>'; ligne += '<td class=prx>' + livres[i].prix + '</td>'; ligne += '<td class=ach>' + '<button type="button">Button ' + i + '</button>' + '</td>'; ligne += '</tr>'; tbody.innerHTML += ligne; table.appendChild(tbody); } } var data = [{First: "first", auteur: 100, titre: 200, prix: 300}, {Second: "second", auteur: 150, titre: 250, prix: 350}, {Third: "third", auteur: 200, titre: 300, prix: 400}] afficherCatalogue(data);
/* CSS */ table { text-align: center; } thead td { font-weight: 700; } td { padding: 10px 10px; }
<!-- HTML --> <table id="table"> <thead> <tr> <td>1</td> <td>2</td> <td>3</td> <td>4</td> <td>5</td> </tr> </thead> </table>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.