HTMLTableRowElementï¼cells 屿§
åºçº¿
广æ³å¯ç¨
èª 2015å¹´7æ èµ·ï¼æ¤ç¹æ§å·²å¨ä¸»æµæµè§å¨ä¸å¾å°æ¯æï¼å¯å¨å¤§å¤æ°è®¾å¤åæµè§å¨çæ¬ä¸æ£å¸¸ä½¿ç¨ã
HTMLTableRowElement æ¥å£ç cells åªè¯»å±æ§è¿åä¸ä¸ªè¡ä¸å
å«åå
æ ¼ç卿 HTMLCollectionãHTMLCollection æ¯å¨æçï¼ä¸å½åå
æ ¼æ·»å æç§»é¤æ¶å¯èªå¨æ´æ°ã
å¼
ä¸ä¸ªå®æ¶ç HTMLTableCellElement 对象ç HTMLCollectionã
示ä¾
æ¤ç¤ºä¾ä½¿ç¨ HTMLTableRowElement.cells å±ç¤ºè¡ä¸åå
æ ¼çæ°éã
HTML
html
<table>
<thead>
<tr>
<th>C1</th>
<th>C2</th>
<th>C3</th>
<th>C4</th>
<th>C5</th>
</tr>
</thead>
<tbody>
<tr>
<td>åå
æ ¼ 1</td>
<td>åå
æ ¼ 2</td>
</tr>
</tbody>
</table>
<button id="add">æ·»å åå
æ ¼</button>
<button id="remove">ç§»é¤æåçåå
æ ¼</button>
<div>第ä¸è¡æ <output>2</output> 个åå
æ ¼ã</div>
JavaScript
js
// è·åç¸å
³æ¥å£å
ç´
const bodySection = document.querySelectorAll("tbody")[0];
const row = bodySection.rows[0]; // éæ©è¡¨æ ¼ä½é¨åç第ä¸è¡
const cells = row.cells; // é忝卿çï¼å æ¤æ»æ¯ææ°ç
const cellNumberDisplay = document.querySelectorAll("output")[0];
const addButton = document.getElementById("add");
const removeButton = document.getElementById("remove");
function updateCellNumber() {
cellNumberDisplay.textContent = cells.length;
}
addButton.addEventListener("click", () => {
// å¨ç¬¬ä¸è¡çæ«å°¾æ·»å åå
æ ¼
const newCell = row.insertCell();
newCell.textContent = `åå
æ ¼ ${cells.length}`;
// æ´æ°è¡æ°
updateCellNumber();
});
removeButton.addEventListener("click", () => {
// ä»è¡¨æ ¼ä½å é¤è¡
row.deleteCell(-1);
// æ´æ°è¡æ°
updateCellNumber();
});
ç»æ
è§è
| è§è |
|---|
| HTML > # dom-tr-cells > |