HTMLTableSectionElementï¼insertRow() æ¹æ³
Baseline
Widely available
This feature is well established and works across many devices and browser versions. Itâs been available across browsers since â¨2015å¹´7æâ©.
HTMLTableSectionElement æ¥å£ç insertRow() æ¹æ³å¨ç»å®çè¡¨æ ¼åæ®µå
ç´ ï¼<thead>ã<tfoot> æ <tbody>ï¼æå
¥ä¸ä¸ªæ°è¡ï¼<tr>ï¼ï¼ç¶åè¿åæ°è¡çå¼ç¨ã
夿³¨ï¼insertRow() å°è¡ç´æ¥æå
¥å°å段ï¼sectionï¼ä¸ï¼è¯¥è¡ä¸éè¦åä½¿ç¨ Document.createElement() å建æ°ç <tr> å
ç´ é£æ ·åç¬è¿½å ã
è¯æ³
insertRow()
insertRow(index)
åæ°
indexå¯é-
æ°è¡çè¡ç´¢å¼ï¼å¦æ
indexæ¯-1æè çäºè¡æ°ï¼æ°è¡ä½ä¸ºæåä¸è¡éå ã妿çç¥indexï¼åé»è®¤å¼æ¯-1ã
è¿åå¼
ä¸ä¸ªå¼ç¨æ°è¡ç HTMLTableRowElementã
å¼å¸¸
IndexSizeErrorDOMException-
妿
index大äºè¡æ°æå°äº-1ï¼åæåºæ¤å¼å¸¸ã
示ä¾
å¨è¿ä¸ªç¤ºä¾ä¸ï¼æä¸¤ä¸ªæé®å
è®¸ä½ å¯¹è¡¨æ ¼ä¸»ä½æ·»å åç§»é¤è¡ï¼å®è¿ä½¿ç¨è¡¨ä¸å½åè¡æ°æ´æ° <output> å
ç´ ã
HTML
<table>
<thead>
<th>å 1</th>
<th>å 2</th>
<th>å 3</th>
</thead>
<tbody>
<tr>
<td>X</td>
<td>Y</td>
<td>Z</td>
</tr>
</tbody>
</table>
<button id="add">æ·»å ä¸è¡</button>
<button id="remove">ç§»é¤æåä¸è¡</button>
<div>è¡¨æ ¼ä¸»ä½æ <output>1</output> è¡ã</div>
JavaScript
// è·åç¸å
³æ¥å£å
ç´
const bodySection = document.querySelectorAll("tbody")[0];
const rows = bodySection.rows; // é忝卿çï¼å æ¤å
¶æ»æ¯ææ°ç
const rowNumberDisplay = document.querySelectorAll("output")[0];
const addButton = document.getElementById("add");
const removeButton = document.getElementById("remove");
function updateRowNumber() {
rowNumberDisplay.textContent = rows.length;
}
addButton.addEventListener("click", () => {
// å¨ä¸»ä½çæ«å°¾æ·»å ä¸ä¸ªæ°è¡
const newRow = bodySection.insertRow();
// 卿°è¡å
æ·»å åå
æ ¼
["A", "B", "C"].forEach(
(elt) => (newRow.insertCell().textContent = `${elt}${rows.length}`),
);
// æ´æ°è¡è®¡æ°
updateRowNumber();
});
removeButton.addEventListener("click", () => {
// ä»ä¸»ä½å é¤è¡
bodySection.deleteRow(-1);
// æ´æ°è¡è®¡æ°
updateRowNumber();
});
ç»æ
è§è
| Specification |
|---|
| HTML > # dom-tbody-insertrow > |