javascript - 使用 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="";
}
我会很感激任何关于我可以改变的建议!
解决方案
尝试这个:
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
推荐阅读
- python - 运行 manage.py 文件时 Django 显示错误
- polymer - Polymer 3.0 中的去抖器
- php - 在 foreach 循环内的 JSON 结果中显示键名
- javascript - 在Angular中单击按钮时移动文本区域?
- powershell - 找不到与参数名称“目录”匹配的参数 - 注册表项
- node.js - 如何使用 express 和 xapi 与 vtc-lrs 包连接 mongo db LearningLocker_v2
- php - go daddy主机服务器上的php邮件功能不发送附件而是在其他服务器上发送
- javascript - Vue.Js axios 获取请求未通过
- vala - Flatpak 捆绑 libmysqlclient
- javascript - Vue-Component 中的 addEventListener 和 vanilla JS