首页 > 解决方案 > 使用 javascript 将模式中的输入添加到新表行

问题描述

我有一个带有 2 个输入字段的模式和一个带有两列的表格。我正在尝试编写一个函数,在单击按钮时向表中添加一个新行。但是,当我测试我的代码时,什么也没有发生。

输入字段的 id 为“modal_type”和“modal_price”,表的 id 为“acc_table1”

JS:

{
         var new_acc=document.getElementById("modal_type").value;
         var new_bal=document.getElementById("modal_price").value;

         var table=document.getElementsById("acc_table1");
         var table_len=(table.rows.length)-1;
         var row = table.insertRow(table_len).outerHTML="<tr id='acc_row"+table_len+"'><td id='acc_name"+table_len+"'>"+new_acc+"</td><td id='acc_balance"+table_len+"'>"+new_bal+"</td></tr>";

         document.getElementById("modal_type").value="";
         document.getElementById("modal_price").value="";
       }

我会很感激任何关于我可以改变的建议!

标签: javascript

解决方案


尝试这个:

const newRow = table.insertRow(-1);                // appends a new row 
newRow.itemId = 'acc_row';                         // set item id to the new row 
const accCell = newRow.insertCell(0);              // add a cell to the new row at index 0
accCell.itemId = 'acc_name';                       // set item id to the cell
const accText = document.createTextNode(new_acc);  // create a text node for new_acc
accCell.appendChild(accText);                      // set text node to acc cell
const balCell = newRow.insertCell(1);              // add a cell to the new row at index 1
balCell.itemId = 'acc_balance';                    // set item id to the cell
const balText = document.createTextNode(new_bal);  // create a text node for new_bal 
balCell.appendChild(balText);                      // set text node to bal cell

推荐阅读