目的
我希望能够使用具有三列的javascript在html表中添加一行。我正在创建一个表,用户可以在其中输入自己的文本,并将文本以及其他两个信息添加到表中的三列中。我拥有的当前代码不会显示新行。该代码还包含拖放功能,用户可以单击该行并将其拖动到表格的其他位置。我要求提供有关为什么为什么当我单击单击按钮时不向表中添加新行的指导。
Javascript
function addRow(mytable) {
var newItem = document.querySelector('.input').value;
var category = document.createTextNode("Cook");
var time = document.createTextNode("time");
document.querySelector('.input').value = '';
// Get a reference to the table
if (newItem != '') {
var tableRef = document.getElementById(mytable);
var attr = document.createAttribute('draggable');
attr.value = 'true';
// Insert a row at the end of the table
var newRow = tableRef.insertRow(-1);
newRow.setAttributeNode(attr);
newRow.className = 'draggable';
// Insert a cell in the row at index 0
var newCell = newRow.insertCell(0);
var newCell2 = newRow.insertCell(1);
var newCell3 = newRow.insertCell(2);
var newText = newItem;
var newText2 = category;
var newText3 = time;
newCell.appendChild(newText);
newCell2.appendChild(newText2);
newCell3.appendChild(newText3);
addEventsDragAndDrop(newRow);
}
}
javascript单击
btn.addEventListener('click', function(){addRow(mytable);});
HTML
<table id="mytable">
<tr>
<th>Component</th>
<th>Category</th>
<th>Time</th>
</tr>
<tr class="draggable" id="draggable" draggable="true">
<td>Food goes here</td>
<td>Cook</td>
<td>10</td>
</tr>
<div id="addRow"></div>
</table>
下面很少进行调整,但需要更多细节,组件自动输入一个文本,但烹饪/时间可以添加更多文本
function addRow(mytable) { var newItem = document.createTextNode(document.querySelector('.input').value); var category = document.createTextNode("Cook"); var time = document.createTextNode("time"); document.querySelector('.input').value = ''; // Get a reference to the table if (newItem != '') { var tableRef = document.getElementById(mytable); var attr = document.createAttribute('draggable'); attr.value = 'true'; // Insert a row at the end of the table var newRow = tableRef.insertRow(-1); newRow.setAttributeNode(attr); newRow.className = 'draggable'; // Insert a cell in the row at index 0 var newCell = newRow.insertCell(0); var newCell2 = newRow.insertCell(1); var newCell3 = newRow.insertCell(2); var newText = newItem; var newText2 = category; var newText3 = time; newCell.appendChild(newText); newCell2.appendChild(newText2); newCell3.appendChild(newText3); addEventsDragAndDrop(newRow); } } document.getElementById('btn').addEventListener('click', function(){addRow('mytable');});
<table id="mytable"> <tr> <th>Component</th> <th>Category</th> <th>Time</th> </tr> <tr class="draggable" id="draggable" draggable="true"> <td>Food goes here</td> <td>Cook</td> <td>10</td> </tr> <div id="addRow"></div> </table> <label for='component'>component</label> <input class='input' id='component' /> <button id='btn'>add component</button>