在 Javascript 的单元格内创建 div

Create div within a cell in Javascript

我在使用 Javascript 动态创建单元格后创建 div 时遇到问题。我的目标是能够在下面添加完全相同的原始 table 行及其内容。下面是 HTML 代码:

      <table width="100%" id="processTable">
    <tr>
    <td id="ProcessDetails"><div id="description">Replace with description.</div>
    <div id="QuestionToAnswer"><b>Replace with a question answerable by YES or NO</b></div>
    </td>
        <td id="AvailableAnswersColumn">
        <p id="option1"><a href="#YES">YES</a></p>
        <p id="option2">NO: Proceed to next question</p>
        </td>
    </tr>
<!--Insert new table row if needed-->
    </table>
    <div id="footer">
    <input type="button" value="Insert Table Row" id="CreateRow" class="CreateRow" onclick="insertRow()" />
    </div>

这是Javascript

<script>
function insertRow() {
    var table = document.getElementById("processTable");
    var row = table.insertRow(1);
    var cell1 = row.insertCell(0);
    var cell2 = row.insertCell(1);
    cell1.innerHTML = //within this cell should be created the div ids "description" + "QuestionToAnswer";
    cell2.innerHTML = //within this cell should be created the paragraph with ids "option1" + "option2";;
    cell1.setAttribute("id", "ProcessDetails", 0);
    cell2.setAttribute("id", "AvailableAnswersColumn", 1);
}
</script>

请帮忙。

document.createElement 会成为你的朋友。

var div = document.createElement("div");
div.innerHTML = "Replace with description.";
cell1.appendChild(div);

使用 document.createElement(<tagname>),您可以使用 JavaScript 代码创建您想要的任何 html 元素。您可以使用 appendChild 将其附加到单元格。由于 div 在我的示例中是一个对象和对 DOM 节点的引用,因此您可以为其设置事件处理程序等