gpt4 book ai didi

jquery - 在html表格中动态添加新行

转载 作者:行者123 更新时间:2023-12-01 07:04:14 25 4
gpt4 key购买 nike

当用户在任意行的最后一个单元格中按enter键时,我能够动态地将新行添加到html表格中。

JSFiddle DEMO

但是,目前它会添加新行,无论当前行位置如何。我只想当用户在最后一个 tr

的最后一个 td 中按 enter 键时添加新行

最佳答案

您需要将 keyup 与您不想注册的 keylistener 的 td 解除绑定(bind)。此代码片段将采用您的 addNewRow() 并设置一个 previousLastTable ,它将与 previousLastTable.off("keyup"); 解除绑定(bind),从而删除监听器。唯一的事件监听器将是最后一个 tr

的最后一个 td

$(function() {
// Change the selector if needed
var $table = $('.mt-table-edit');

addNewRow();

var previousLastTable;


function addNewRow() {
//get row template. We must use html() for new instance other event handler will get attached to last row
var $tr = $("<tr><td><input/></td><td><input/></td><td><input/></td><td><input/></td></tr>");

if (previousLastTable) {
previousLastTable.off("keyup");
}


$tr.find("td").eq($tr.find("td").length - 1).keyup(function(e) {
if (event.keyCode === 13) {
addNewRow();
}
});

// add template after the last row
$table.find("tbody:last-child").append($tr);

// focus on firt input of newly added row
$tr.find("td:first input").focus();

previousLastTable = $tr.find("td").eq($tr.find("td").length - 1);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>
To add new row press enter key in the last cell of the row
</p>
<table class="mt-table-edit">
<thead>
<tr>
<th>Street</th>
<th>State</th>
<th>City</th>
<th>Country</th>
</tr>
</thead>
<tbody>

</tbody>
</table>

关于jquery - 在html表格中动态添加新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55172787/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com