我有一個向表格添加行的按鈕。該表可編輯點擊(類似於這裏發現的一個:http://www.9lessons.info/2011/03/live-table-edit-with-jquery-and-ajax.html) 但是,我從數據庫中獲取我的表數據。每個<td>
都有一個data-field
屬性,該屬性與數據庫中的<td>'s
字段名稱對應。現在,爲了讓添加的表格行可以像其他行一樣進行編輯,我需要在其正上方的單元格中標記<td>'s
data-field
和data-field
。我已經嘗試了幾種不同的方法,但不斷地做出來。這裏是我的添加行腳本:獲取上述td單元格的數據字段
<script type="text/javascript">
/*
Add a new table row to the bottom of the table
*/
$(document).ready(function()
{
$(".add").click(function()
{
$("#table").each(function()
{
var $table = $(this);
var id=$('#table tr:last').attr('id');
var $tr = $("#table").children('tr');
var $th = $(this).closest('table').find('th').eq($(this).index());
// Number of td's in the last table row
var n = $('tr:last td', this).length;
var tds = '<tr class="edit_tr" id="' + id++ + '">';
for(var i = 0; i < n; i++)
{
tds += '<td class="edit_td"><input type="text" class="editbox" id="' +
id + '" data-field="' + $th + '"/> </td>';
console.log($th);
}
tds += '</tr>';
//console.log(tds);
if($('tbody', this).length > 0)
{
$('tbody', this).append(tds);
}else {
$(this).append(tds);
}
});
});
});
</script>
現在,請注意var $th = $(this).closest('table').find('th').eq($(this).index());
。這是我得到的最接近的。但是,我不想通過th
訪問。我想通過數據字段訪問。有任何想法嗎?
爲什麼不直接通過'$ .attr('data-field);' – Darren
因爲我不知道如何獲取正在創建的單元格的數據字段。我可能會創建所有最後的'tr's'數據字段'的數組,但我不知道如何去做這樣的事情。然後,我可以在我的for循環中執行'array [i]'。 –