J'ai une fonction JavaScript qui crée une table avec 3 lignes 2 cellules.
Quelqu'un pourrait-il me dire comment je peux créer la table ci-dessous en utilisant ma fonction (je dois le faire pour ma situation)?Créer un tableau en utilisant Javascript
Mon HTML:
<table width="100%" border="1">
<tr>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td rowspan="2"> </td>
</tr>
<tr>
<td> </td>
</tr>
</table>
JavaScript:
function tableCreate() {
//body reference
var body = document.getElementsByTagName("body")[0];
// create elements <table> and a <tbody>
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");
// cells creation
for (var j = 0; j <= 2; j++) {
// table row creation
var row = document.createElement("tr");
for (var i = 0; i < 2; i++) {
// create element <td> and text node
//Make text node the contents of <td> element
// put <td> at end of the table row
var cell = document.createElement("td");
var cellText = document.createTextNode("cell is row "+j+", column "+i);
cell.appendChild(cellText);
row.appendChild(cell);
}
//row added to end of table body
tblBody.appendChild(row);
}
// append the <tbody> inside the <table>
tbl.appendChild(tblBody);
// put <table> in the <body>
body.appendChild(tbl);
// tbl border attribute to
tbl.setAttribute("border", "2");
}
bonne solution, mais il est préférable de créer les variables en dehors de la boucle –
@Cerbrus Il est bon solution, mais cela ne fonctionne pas avant IE8. La table est ajoutée à l'explorateur DOM mais de toute façon, elle n'est pas visible. Est-ce que quelqu'un sait comment résoudre cela? – bdogru
@bdogru: Pourquoi avez-vous besoin de soutenir IE8? C'est ancien. Google [a abandonné ce navigateur fin 2012] (http://www.computerworld.com/article/2492571/web-apps/google-to-drop-support-for-ie8-on-nov--15.html) – Cerbrus