簡體   English   中英

如何使用JavaScript編輯表格中的HTML

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM