Javascript 防止删除第一行
我有一个可以添加/删除行的表。问题是当我删除第一行时,就不能再添加任何行了。所以,我想防止删除第一行。请问我怎么做 谢谢 jQuery HTMLJavascript 防止删除第一行,javascript,jquery,html,html-table,Javascript,Jquery,Html,Html Table,我有一个可以添加/删除行的表。问题是当我删除第一行时,就不能再添加任何行了。所以,我想防止删除第一行。请问我怎么做 谢谢 jQuery HTML 罗巴/乌斯卢加 Jmj 数量 价格 拉巴特 请选择 大卫·哈塞尔霍夫 迈克尔杰克逊 蒂娜·特纳 请选择 大卫·哈塞尔霍夫 迈克尔杰克逊 蒂娜·特纳 去除 添加 演示 您可以检查行的长度: $(".remove_button").on("click", function () { if ( $('#table tbody tr').lengt
罗巴/乌斯卢加
Jmj
数量
价格
拉巴特
请选择
大卫·哈塞尔霍夫
迈克尔杰克逊
蒂娜·特纳
请选择
大卫·哈塞尔霍夫
迈克尔杰克逊
蒂娜·特纳
去除
添加
演示
您可以检查行的长度:
$(".remove_button").on("click", function () {
if ( $('#table tbody tr').length === 1 ) return;
// ...
});
另一个选项是使用not
方法和first child
选择器:
$(this).closest("tr").not(':first-child').fadeOut()...
或使用CSS隐藏第一行按钮:
#table tbody tr:first-child .remove_button { display: none; }
在这里,您可以根据自己的目标优化该功能
为什么不尝试修复add函数,使其在没有行的情况下仍能工作,而不是阻止删除第一行。这也是一个选项,但我更希望在这种情况下总是只剩下一行。您可以尝试使用一个带有display的临时表:none或直接在javascript中使用一个tr作为模板,该tr为您提供克隆行的模板,并使用addTableRow中的这个可诱惑的行进行克隆,而不是在同一个表中的最后一个tr中进行克隆。也就是说,如果我们不在第一行显示“删除”按钮,是否有一个选项?@targsx是的,您可以在CSS中使用
第一个子项
选择器
$(this).closest("tr").not(':first-child').fadeOut()...
#table tbody tr:first-child .remove_button { display: none; }
$(document).ready(function ($) {
// trigger event when button is clicked
$("button.add").click(function () {
// add new row to table using addTableRow function
addTableRow($("table"));
// prevent button redirecting to new page
return false;
});
$(document).on("click", ".remove_button", removeTableRow );
// function to add a new row to a table by cloning the last row and
// incrementing the name and id values by 1 to make them unique
var rowCount = null;
function addTableRow(table) {
// clone the last row in the table
var $tr = $(table).find("tbody tr:last").clone();
// get the name attribute for the input and select fields
$tr.find("input,select").attr("name", function () {
// break the field name and it's number into two parts
var parts = this.id.match(/(\D+)(\d+)$/);
// create a unique name for the new field by incrementing
// the number for the previous field by 1
return parts[1] + ++parts[2];
// repeat for id attributes
}).attr("id", function () {
var parts = this.id.match(/(\D+)(\d+)$/);
return parts[1] + ++parts[2];
});
// append the new row to the table
$(table).find("tbody tr:last").after($tr);
$tr.hide().fadeIn('slow');
// row count
rowCount = 0;
$("#table tr td:first-child").text(function () {
return ++rowCount;
});
};
function removeTableRow(){
var $tbody = $(this).parents('tbody'),
$trLen = $tbody.find('tr').length
if ( $trLen === 1 ) return false;
$(this).parents("tr").fadeOut('slow', function () {
$(this).remove();
rowCount = 0;
console.log( rowCount );
$("#table tr td:first-child").text(function () {
return ++rowCount;
});
});
}
});