请有人告诉我为什么第一行得到索引值 1 但每隔一个新行也得到 1 而不是 2,3,4 等等。
<!DOCTYPE html>
<head>
<meta charset="utf-8">
</head>
<body>
<form>
<table>
<thead>
<tr>
<th scope="col">Track</th>
<th scope="col">Album</th>
<th scope="col">Artist</th>
</tr>
</thead>
<tbody>
<tr>
<td><input name="track[0]" id="track"></td>
<td><input name="album[0]" id="album"></td>
<td>
<select name="artist[0]" id="artist">
<option value="">Please select</option>
<option value="1">Joe Bloggs</option>
<option value="2">Jack Bloggs</option>
<option value="3">Tina Bloggs</option>
</select>
</td>
</tr>
</tbody>
</table>
</form>
<button>Add Row</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
$(document).ready(function($)
{
// trigger event when button is clicked
$("button").click(function()
{
// add new row to table using addTableRow function
addTableRow($("table"));
// prevent button redirecting to new page
return false;
});
function addTableRow(table)
{
var $tr = $(table).find("tr:last").clone();
alert($tr);
var fname = $("#track").attr("name");
var nid = fname.match(/\[(.*?)\]/g);
var idx = nid[0];
idx = idx.replace(/[[\]]/g,'')
var n = fname.split("[");
idx = parseInt(idx) + 1;
$tr.find("input,select").attr("name", n[0] + "[" + idx + "]");
$(table).find("tbody tr:last").after($tr);
};
});
</script>
</body>
每次准备使用 AJAX 帖子时,我似乎无法弄清楚如何每次将每个表元素的“名称”增加 1 时添加一个新行。