简体   繁体   中英

How to edit the HTML inside a table using JavaScript

When I try to add a button on a html table the table won't appear. On the last element of "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> 

I have to add a simple button.

Assuming livres references an array of objects, you need to remove tbody from your table and create the tbody element with JavaScript using the createElement() method.

After creating the element, you can use a for loop to retrieved the required data from each object in the array and assign it to the ligne variable.

After looping through the objects, you can then populate the tbody element you just created with the retrieved data from the ligne variable using innerHTML() property and then append the tbody element to your table using the appendChild() method like this:

 /* 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM