【发布时间】:2019-07-20 04:51:33
【问题描述】:
我正在尝试创建一个工具栏来修改表table_content_inv。
列管理有效,但导致我出现问题的是行,无论是添加还是删除。这是因为我指定了一个 thead 和一个 tbody 会导致 indexes 出现问题。当我选择 thead 的一个元素(行索引 0)时,它将被添加到 tbody(行索引 0) - 我知道是我指定了它,但我不知道如何继续。
我使用函数 .index() 获取 tds 的索引,而无需管理元素是在 thead 还是 tbody 中。 我应该改变从 td 元素中检索索引(或其他内容)的方式,还是以某种方式添加元素在 thead 或 tbody 中的事实?
//set selected row
var rowIndex = '';
$(document).on('click', '#table_content_inv td', function() {
rowIndex = $(this).closest('tr').index();
});
//delete selected row
$(document).on('click', '#button_del_row', function() {
$('#table_content_inv > tbody > tr').eq(rowIndex).remove();
});
//add row to table
$(document).on('click', '#button_add_row', function() {
var indexNewRow = rowIndex + 1;
var newRow = '<tr>';
var colCount = document.getElementById('table_content_inv').rows[0].cells.length;
for (i = 0; i < colCount; i++) {
newRow += '<td>new entry</td>';
}
newRow += '</tr>';
$('#table_content_inv > tbody > tr').eq(rowIndex).after(newRow);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table_content_inv">
<thead>
<tr>
<td>entry</td>
<td>entry</td>
<td>entry</td>
</tr>
</thead>
<tbody>
<tr>
<td>entry</td>
<td>entry</td>
<td>entry</td>
</tr>
<tr>
<td>entry</td>
<td>entry</td>
<td>entry</td>
</tr>
</tbody>
</table>
<div id="toolbar-content" class="toolbar-content">
<button id="button_add_row" class="button button-secondary" type="button">Ajout ligne</button>
<button id="button_del_row" class="button button-secondary" type="button">Supprimer ligne</button>
</div>
【问题讨论】:
-
HTML 中的按钮在哪里?
-
刚刚添加@RoryMcCrossan
标签: jquery