首页 > 解决方案 > 关于使用 JavaScript 和 DOM 接口遍历 HTML 表格的问题

问题描述

我按照这里的例子:https ://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Traversing_an_HTML_table_with_JavaScript_and_DOM_Interfaces

但我有两件事我无法弄清楚。

首先是如何为所有 td 元素添加类名?

第二,我如何将此表注入名为“main”的 div,而不是 document.getElementsByTagName("body")[0];

document.getElementsByTagName("body") 末尾的[0]我不是很懂,为什么需要呢?

标签: javascript

解决方案


第一个是如何为所有的td元素添加一个类名?第一个是如何为所有的td元素添加一个类名?

类列表.add

第二,我如何将这个表注入一个名为“main”的 div

getElementById

我不太明白 document.getElementsByTagName("body") 末尾的 [0]

因为 getElementsByTagName 是通用的。它可以返回任何标签的倍数。[0] 说“给我第一个”,因为它是 BODY,我们几乎可以肯定只有一个。

    function start() {
        // get the reference for the body
        var mybody = document.getElementById("main");

        // creates <table> and <tbody> elements
        mytable = document.createElement("table");
        mytablebody = document.createElement("tbody");

        // creating all cells
        for(var j = 0; j < 3; j++) {
            // creates a <tr> element
            mycurrent_row = document.createElement("tr");

            for(var i = 0; i < 4; i++) {
                // creates a <td> element
                mycurrent_cell = document.createElement("td");
                mycurrent_cell.classList.add("myClass");
                // creates a Text Node
                currenttext = document.createTextNode("cell is row " + j + ", column " + i);
                // appends the Text Node we created into the cell <td>
                mycurrent_cell.appendChild(currenttext);
                // appends the cell <td> into the row <tr>
                mycurrent_row.appendChild(mycurrent_cell);
            }
            // appends the row <tr> into <tbody>
            mytablebody.appendChild(mycurrent_row);
        }

        // appends <tbody> into <table>
        mytable.appendChild(mytablebody);
        // appends <table> into <body>
        mybody.appendChild(mytable);
        // sets the border attribute of mytable to 2;
        mytable.setAttribute("border","2");
    }

start();
.myClass {
color:red;
}
<div id="main"></div>


推荐阅读