2014-12-02 2 views
1

Я клонирую строку и добавлю ее в конец таблицы следующую функцию add_record(). Мой вопрос заключается в том, как добавить его в начало таблицы. Я попытался с помощьюКак добавить строку в начало таблицы с помощью javascript

$("#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); 
    } 
+0

возможно дубликат [Javascript Add Table Row] (http://stackoverflow.com/questions/13870348/javascript-add-table-row) – isherwood

+0

возможный дубликат ответ replacong все innerHtml таблицы. Мне нужен ответ, который добавляет только первую строку, так как таблица большая. – yaron89

ответ

1

Используйте встроенную функцию 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

Смежные вопросы