jquery で tr:last コマンドを使用すると、固有のバグが発生します。
テンプレート行の .clone() に基づく動的テーブルがありました。
行を追加するときに、行数を増やしてフィールドに名前を付けたい
ただし、行を削除することもできるため、増分係数は最後の行の ID を調べて、カウントが新しい行の var ではなく、max+1 であるかどうかを確認する必要があります。(事実上、クローン行により最大+2)
私が抱えている落とし穴は、それが毎回機能するということです...それは非常に奇妙です.
3 つの行を追加するサンプル アラート シーケンスを次に示します。
最大 = 4 カウント = 5
最大 = 4 カウント = 6
最大 = 6 カウント = 7
したがって、5 の最大値を見つけることは実際には行われません。
function addrow(table){
var className;
var count = $("#"+table+" tbody tr").length;
//since we have a th that server-side prints, no need to count++. if th removed, count++ this.
//in case of rows removed, need to find last row and check its number...
var max = $("#"+table+" tbody tr:last").attr('id').split("_").pop();
alert('max='+max+' count='+count);
if(parseInt(max)+2>count){
count = max;
}
var $clone = $("#"+table+" tbody tr:first").clone();
$clone.attr({
id: "dynrow_" +$('#'+table).attr("id")+"_"+ count.toString(),
"class": "" , //remove template class
style: "" // remove "display:none"
});
$clone.find("input,select,textarea").each(function(){
var xname = $(this).attr("name") + count.toString();
$(this).attr({
id: $(this).attr("id") + count.toString(),
name: xname
});
//populate fields that don't exist on page build by reading datacollector div with html5 data
$(this).val($("#datacollector").data(xname));
});
if(count%2==0){
className="even";
}
else{
className="odd";
}
$clone.find("td").each(function(){
if($(this).hasClass("xcol")){
className = className + ' xcol';
}
$(this).attr({
'class': className
});
});
$clone.find("label").each(function(){
$(this).attr({
"for": $(this).attr("for") + count.toString()
});
});
$clone.find("a.removerow").each(function(){
$(this).attr({
id: $(this).attr("id") + count.toString()
});
});
$("#"+table+" tbody").append($clone);
//update row counter
$("#initialrows_"+table).val(count.toString());
}
<input type="hidden" id="initialrows_table_aaa" name="initialrows_table_aaa" value="1">
<table id="table_aaa" class="dynrow">
<thead>
<tr>
<th>A</th>
<th>B</th>
<th>C</th>
</tr>
</thead>
<tbody>
<!--template-->
<tr class="template" id="template_aaa" style="display:none;">
<td class="even"><label for="inp_16">a</label><input type="text" name="a_" id="inp_16" value=""></td>
<td class="even"><label for="inp_17">b</label><select id="inp_17" name="b_">
<option value="">Select</option>
<option value="A">A</option>
</select>
</td>
<td class="even"><label for="inp_18">c</label><select id="inp_18" name="c_">
<option value="">Select</option>
<option value="A">A</option>
</select>
</td>
</tr>
<!--end template-->
</tbody>
ワーキングフィドル、 http://jsfiddle.net/briansol/5h4cM/1/
何か案は?