Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/382.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
javascript在表中添加新行_Javascript_Html - Fatal编程技术网

javascript在表中添加新行

javascript在表中添加新行,javascript,html,Javascript,Html,我试图通过javascript在表中添加新行。 我想在最后一行的前面插入一行,在表中插入每一新行时,标签中的数字也会随之递增 <input type=button value='Add Row' /> <table cellspacing=0 cellpadding=4 id="table"> <tr><td>Number 1:</td><td><input value=20 style="width:30px" t

我试图通过javascript在表中添加新行。 我想在最后一行的前面插入一行,在表中插入每一新行时,标签中的数字也会随之递增

<input type=button value='Add Row' />

<table cellspacing=0 cellpadding=4 id="table">
<tr><td>Number 1:</td><td><input value=20 style="width:30px" type=text  maxlength=2/></td></tr>
<tr><td>Number 2:</td><td><input value=25 style="width:30px" type=text  maxlength=2/></td></tr>
<tr><td style="border-top:solid 1px black;border-bottom:solid 1px black;">Sum:</td><td style="border-top:solid 1px black;border-bottom:solid 1px black;"><div>45</div></td></tr>
</table>
这是表的代码,我希望它位于'number 2'行下,但在sum行之前。 每增加一行,标签就被改为3号:例如4号等等。 你知道我怎么做吗。我只需要使用javascript,不允许使用外部工具或jquery。 提前谢谢你,拉齐尔

懒得粘贴代码

给出数字1,2,3。。您应该创建行ID,如“row1”、“row2”

放置一个隐藏变量并根据生成的行增加其值

确保表中有一个tbody元素

var table = document.getElementById('table');

var button = document.getElementsByTagName('input')[0];

button.onclick = function() {
    var clone = table.rows[table.rows.length - 2].cloneNode(true);
    clone.cells[0].firstChild.data = 
       clone.cells[0].firstChild.data.replace(/(\d+):/,function(str,g1) { 
                                                          return (+g1 + 1) + ':'; 
                                                       });
    table.tBodies[0].insertBefore(clone, table.rows[table.rows.length-1]);
};
另外,将最后一行放在元素中可能是有意义的,这会稍微改变一些情况

button.onclick = function() {
    var clone = table.rows[table.rows.length - 2].cloneNode(true);
    clone.cells[0].firstChild.data =
        clone.cells[0].firstChild.data.replace(/(\d+):/,function(str,g1) { 
                                                           return (+g1 + 1) + ':'; 
                                                        });
    table.tBodies[0].appendChild(clone);
};

谢谢你的回复,正如我所看到的,但是有一件事,当点击按钮时,我如何使用js代码?因为表单上还有一个按钮与添加一个字段无关。我可以在按钮上执行onclick事件并使用上面的代码吗?感谢您的帮助,最佳解决方案将取决于您的实际HTML标记。了解输入和表之间的关系会有所帮助。