javascript - 如何使用 javascript 将行添加到表的开头

标签 javascript

我克隆一行并将其附加到以下函数 add_record() 的表末尾。 我的问题是如何将其附加到表的开头。 我尝试使用

$("#main_table_id tbody").prepend(clone) 

$("#main_table_id tbody").prepend(clone.innerHtml)

但是没有成功。

function add_record(){      
        var row = document.getElementById("template_no_1_id"); 
        var table = document.getElementById("main_table_id"); 
        var clone = row.cloneNode(true); 
        clone.id = "newID"; 
        table.appendChild(clone); 
    }

最佳答案

使用 native 函数 insertRow。

<table id="TableA">
<tr>
<td>Old top row</td>
</tr>
</table>
<script type="text/javascript">

function addRow(tableID) {
  // Get a reference to the table
  var tableRef = document.getElementById(tableID);

  // Insert a row in the table at row index 0
  var newRow   = tableRef.insertRow(0);

  // Insert a cell in the row at index 0
  var newCell  = newRow.insertCell(0);

  // Append a text node to the cell
  var newText  = document.createTextNode('New top row');
  newCell.appendChild(newText);
}

// Call addRow() with the ID of a table
addRow('TableA');

</script>

信用:https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableElement.insertRow

关于javascript - 如何使用 javascript 将行添加到表的开头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27258077/

相关文章:

javascript - Node.js - ssh2-sftp-client 获取多个文件错误

javascript - 在 Javascript 中单击时从按钮的动态 ID 获取值

javascript - "u"元素内的属性

javascript - 无法在我的页面内显示旋钮饼图,饼图现在显示

javascript - fetch() 不发送标题?

javascript - 在鼠标悬停时,在 JavaScript 中更改图片

javascript - 未捕获的类型错误 : addEventListener not working when calling external function instead of anonymous function

javascript - 在事件监听器中访问 `this`

javascript - 如何检查每年的日期是否已达到或过期

javascript - AngularJS:使用 $http 请求文件(json 内容)时发生 SyntaxError