撤销
我希望能够使用javascript将一行和三列添加到html中的表中。我正在创建一个表,用户可以在其中输入自己的文本,并将文本和另外两条信息一起添加到表中的三列中。我所拥有的当前代码将不会显示新行。该代码还包括一个拖放功能,用户可以在其中单击行并将其拖动到表中的不同位置。我正在寻求指导,解释为什么当我按下点击按钮时,它不会向表中添加新行。edit:代码在更新后可以工作,但else语句没有任何作用。
Javascript
function addRow(mytable) {
var food = document.createTextNode(document.querySelector('.input').value);
var category = document.createTextNode(document.querySelector('.input2').value);
var time = document.createTextNode(document.querySelector('.input3').value);
document.querySelector('.input').value = '';
document.querySelector('.input2').value = '';
document.querySelector('.input3').value = '';
// Get a reference to the table
if (food !== '') {
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 = food;
var newText2 = category;
var newText3 = time;
newCell.appendChild(newText);
newCell2.appendChild(newText2);
newCell3.appendChild(newText3);
addEventsDragAndDrop(newRow);
}
//not working for some reason
else {
document.getElementById("msg").innerHTML = "Please enter a name";
}
}
javascript点击
document.getElementById('btn').addEventListener('click', function( {addRow('mytable');});
HTML
<table id="mytable">
<tr>
<th>Component</th>
<th>Category</th>
<th>Time</th>
</tr>
<div id="addRow"></div>
</table>
下面很少有调整,但需要更多细节,atm只为组件输入一个文本,但可以为烹饪/时间添加更多
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>