0
我試圖在javascript中創建一個表格,並在其上放置了一個標題。我試圖納入這個SO question的答案,但也許我沒有把它包含在正確的地方。表格的主體完美地工作,但標題作爲一堆文本附加到頂部而不是格式良好的標題。下面是代碼:在javascript中添加動態表格表格標題
function generate_table() {
// get the reference for the body
var body = document.getElementsByTagName("body")[0];
// creates a <table> element and a <tbody> element
var tbl = document.createElement("table");
//var header = document.createElement("header");
var header = '<tr><th>Country</th><th>City</th></tr>';
//var header = "<th>Header</th>";
var tblBody = document.createElement("tbody");
// creating all cells
for (var i = 0; i < results.weak_sent.length; i++) {
// creates a table row
var row = document.createElement("tr");
for (var j = 0; j < 2; j++) {
// Create a <td> element and a text node, make the text
// node the contents of the <td>, and put the <td> at
// the end of the table row
var cell = document.createElement("td");
if (j == 0) {
var cellText = document.createTextNode(results.weak_sent_num[i]);
} else {
var cellText = document.createTextNode(results.weak_sent[i]);
}
cell.appendChild(cellText);
row.appendChild(cell);
}
// add the row to the end of the table body
tblBody.appendChild(row);
}
tbl.append(header)
// put the <tbody> in the <table>
tbl.appendChild(tblBody);
// appends <table> into <body>
body.appendChild(tbl);
// sets the border attribute of tbl to 2;
tbl.setAttribute("border", "2");
}
它打印的行和列正確的,但不是解釋<tr><th>
HTML標籤,它只是打印出來爲文本。我也注意到,如果表格文本包含任何HTML標記,例如<strong>
或<b>
,它們也會以純文本形式返回。我怎樣才能讓他們被讀爲HTML。我也有一個CSS頁面,但沒有重置或任何(有意)影響粗體或表格的使用。這裏是我的結果
<tr><th>Country</th><th>City</th></tr>
1 Row 1 text
2 Row <b>2</b> text
第二種解決方案完全適用於我,但第一個打印頭國家第二列並沒有什麼第一列上方的上方。 – jss367
@ jss367感謝您的輸入,我編輯了這個。現在兩者都在工作 –