如何使用Javascript创建动态表?

如何使用Javascript创建动态表?,javascript,django,Javascript,Django,我正在尝试创建一个动态html表,但我还不能做到这一点 我会付出我所做的一切 这就是代码 <table id="myTable"> <tr id="tr"> <th>Students Name</th> <th>Average</th> </tr> {% for student in teacherStudents %} <tr id="tr

我正在尝试创建一个动态html表,但我还不能做到这一点

我会付出我所做的一切

这就是代码

<table id="myTable">
    <tr id="tr">
        <th>Students Name</th>
        <th>Average</th>
    </tr>
    {% for student in teacherStudents %}
    <tr id="tr2">
        <td id="td">{{ student.Students_Enrollment_Records.Student_Users }}</td>
    </tr>
    {% endfor %}
</table>
<button type="button" value="" class="save" onclick="doTheInsert()" title="Insert New Cell" id="save">&plus;&nbsp;Insert New Cell</button>

<button type="button" value="" class="save" onclick="undoTheInsert()" title="Undo Recent Action" id="unsave">&times;&nbsp;Undo Recent Action</button>

<script>
    var count = 0;

    function doTheInsert() {
        let header = $.find("tr[id='tr']")[0];
        header.append("<th data-id='header'><input type='date'></th>");
        let rows = $.find("tr[id='tr2']");
        for (let i = 0; i < rows.length; i++) {
            rows[i].append("<td data-id='row'><input type='text'/></td>");
        }
    }
</script>

学生姓名
平均值
{teacherStudents%}
{{student.Students\u registration\u Records.student\u Users}
{%endfor%}
&加;插入新单元格
&时代;撤消最近的操作
var计数=0;
函数doTheInsert(){
let header=$.find(“tr[id='tr'])[0];
标题。附加(“”);
让行=$.find(“tr[id='tr2']”);
for(设i=0;i
我想要的是,如果老师点击按钮,它会在日期下添加文本框,具体取决于学生人数和要添加的文本框数量

例如,我单击两次按钮“插入新单元格”

这是我想要的结果,(我将生成静态结果以澄清我想要的)

我得到了什么结果

更新: 当我尝试dirkgroten爵士的答案时,我得到了这个答案

日期将出现在学生姓名和平均数之间

您的
.append()
应用于javascript DOM节点而不是jQuery元素,因为您索引到jQuery元素中

例如,
let header=$(“tr#tr”)
提供所有
元素。执行
头[0]
时,这不再是jQuery元素,而是javascript节点。因此,
append()
与您期望的功能不同:

  • 在javascript中,
    ParentNode.append()
    追加实际字符串,如前所述
  • 在jQuery中,
    elem.append()
您的代码应该如下所示:

function doTheInsert()
    {
        let header=$("tr#tr");  // same as $.find("tr[id='tr2']")
        header.append("<th data-id='header'><input type='date'></th>");

        let rows=$("tr#tr2");
        rows.append("<td data-id='row'><input type='text'/></td>");
    }
函数doTheInsert()
{
let header=$(“tr#tr”);//与$.find(“tr[id='tr2'])相同
标题。附加(“”);
设行=$(“tr#tr2”);
行。追加(“”);
}

问题是
[0]
[i]
。通过这样索引jquery元素,您实际上获得了javascript DOM节点。javascript中的函数
append()
也存在,它会将blob(即非html)作为文本追加。在定义
标题时,请尝试删除
[0]
。而不是在行中循环,只需
行。追加(“”
)。这将使用jquery
append()
,它允许html。我不明白,您不应该有多个id相同的行。这可能会导致意外行为。id对于整个页面是唯一的。改用类。
let header=$.find(“tr[id='tr'])我回答了您的问题,即您附加的内容不是html内容。现在的问题是如何更明智地选择追加或插入的位置。使用不同的jquery选择器在正确的位置追加/插入。当然,如果您按照名称“append”,这将在所选元素的末尾添加元素。您也可以“插入”,例如,在“average”列中添加一个id,然后选择该id。请阅读各种前置、追加或插入方法。而且,这太复杂了