javascript - 尝试将文本框值添加为表格行
问题描述
我正在尝试读取 3 个文本框值:名字、姓氏和年龄,并在单击保存按钮后将它们添加为表格中的一行,但它不起作用。我的功能有什么问题?
function save()
{
var firstName= document.getElementById("txtFname").value;
var lastName=document.getElementById("txtLname").value;
var ageValue=parseInt(document.getElementById("age").value,10);
var table2=document.getElementById("dbtable");
var fNameValue= value.createTextNode(firstName);
var lNameValue= value.createTextNode(lastName);
var agetextnode=value.createTextNode(ageValue);
td1=document.createElement("td");
td2=document.createElement("td");
td3=document.createElement("td");
td1.appendChild(fNameValue);
td2.appendChild(lNameValue);
td3.appendChild(agetextnode);
tr1=document.createElement("tr");
tr1.appendChild(td1);
tr1.appendChild(td2);
tr1.appendChild(td3);
table2.appendChild(tr1);
}
解决方案
如果您可以提供正在使用的完整 HTML/JavaScript 会有所帮助,这样我们就可以看到问题出在哪里。
我还建议扩展您的逻辑以使其更容易进行故障排除。你基本上有3个步骤:
- 获取输入的值
- 为新行生成标记
- 将行追加到表中
这是一个示例,这些示例如何符合您的要求。
function save () {
const age = document.getElementById('age').value;
const first = document.getElementById('firstName').value;
const last = document.getElementById('lastName').value;
const tbody = document.querySelector('#dtable tbody');
tbody.appendChild(createRow(age, first, last));
}
function createRow(age, first, last) {
const tr = document.createElement('tr');
tr.appendChild(createTd(age));
tr.appendChild(createTd(first));
tr.appendChild(createTd(last));
return tr;
}
function createTd(value) {
const td = document.createElement('td');
td.innerText = value;
return td;
}
table {
width: 100%;
}
<input type="number" id="age" placeholder="age" />
<input type="text" id="firstName" placeholder="First Name" />
<input type="text" id="lastName" placeholder="Last Name" />
<button onclick="save()">Save</button>
<table id="dtable">
<thead>
<tr>
<th>Age</th>
<th>First</th>
<th>Last</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
推荐阅读
- c# - 通过从字典访问添加委托时,事件为空
- javascript - 在javascript中围绕路径制作正弦波曲线
- python - 多线程是否有可能提取从外部源流式传输的全局变量?
- android - Android Studio Emulator:进程退出,错误代码为 1
- python-3.x - Pandas Python 如何使用一个数据帧中的通用数据写入不同的数据帧?
- mysql - MySQL SUM 长文本字段,$1.000.00 为 1000
- python - pyqt5 归一化向量
- c - C 结构数组,包含指向结构数组的指针
- javascript - 如果媒体宽度 < x 则更改 HTML
- django - 无法使用 django-filter 过滤