jQuery根据输入添加或删除表行

对不起,如果这太基础了。

  1. 如果当前行数小于用户的需求,我试图向表中添加行。
  2. 同时,如果当前行数超过用户需要,我需要删除额外的行。

我的代码正在运行,但我认为它没有多大意义。 所以我想知道是否有人能纠正我的错误并使我的代码更合理。 (我试图使用两个索引来控制这个添加或删除活动。一个索引检查当前存在的元素并获得用户新输入之间的差异。然后执行添加或删除移动。但我没有这样做。)

另外,是否可以在不改变shape of the first table row?shape of the first table row?情况下调整添加的

的宽度shape of the first table row? 谢谢你的帮助! 这是一个演示 。

HTML

 
Make a selection 1 2 3
App# Month Day Mass Applied (kg/hA) Slow Release (1/day)

JS

 $(document).ready(function () { var i = 1 $('#id_noa').change(function () { var total = $(this).val() $('#noa_header').show() //I was trying to use two indices to control this add or remove activity. One index check the current existed elements and get the difference between user's new input. Then do the add or remove movements. But I failed to do this. while (i <= total) { $('.tab_Application').append(''); i = i + 1; } while (i-1 > total) { $(".tab_Application tr:last").remove(); i=i-1 } $('').appendTo('.tab_Application'); }) }); 

我接受了@ B3aT提出的想法,编辑并充实了这个(可以在我的OP的jsfiddle的叉子上找到 :

 var row_i = 0; function emptyRow() { row_i++; this.obj = $(""); this.obj.append(''); this.obj.append(''); this.obj.append(''); this.obj.append(''); this.obj.append(''); } function refresh(new_count) { if(new_count > 0) { $("#noa_header").show(); } else { $("#noa_header").hide(); } var old_count = parseInt($('tbody').children().length); var rows_difference = parseInt(new_count) - old_count; if (rows_difference > 0) { for(var i = 0; i < rows_difference; i++) $('tbody').append((new emptyRow()).obj); } else if (rows_difference < 0)//we need to remove rows .. { var index_start = old_count + rows_difference + 1; $('tr:gt('+index_start+')').remove(); row_i += rows_difference; } } $(document).ready(function () { $('#id_noa').change(function () { refresh( $(this).val() ); }) }); 

emptyRow函数这么长的原因是我想让列数容易操作。 每列都单独附加,因此更改默认模式很简单。

在html中,我必须添加theadtbody标签,如@ B3aT的回答中所述。 thead包括前两行,因为第1行是选择框,第2行是表的实际标题。 tbody是空的开始。

就改变各行的样式(如调整列宽)而言,最好不要使用表格。 类似于表的行为可以像在列样式中使用float:left一样简单,确保在每行的末尾放置一个带clear:both的div clear:both

在这些情况下,jQuery擅长,让我们玩各种选择器。 首先,您需要分隔表格的标题和正文(thead和tbody)。 (代码未经测试)。

 function refresh(new_count) { //how many applications we have drawed now ? var old_count = parseInt($('tbody').children().count()); //the difference, we need to add or remove ? var rows_difference = parseInt(new_count) - old_count; //if we have rows to add if (rows_difference > 0) { //$('tbody').append() or prepend() new empty rows based on your pattern with a loop } else if (rows_difference < 0)//we need to remove rows .. { var index_start = old_count - rows_difference;//for the LAST X rows $('tr:gt('+index_start+')').remove(); } }