我有一个通过 JS 通过添加/删除行(表单输入)来动态更改的表单/表格。我想创建一个计算行数的列,所以我尝试使用,
$("#rowcount:last").replaceWith( "<td>" + newNum + "</td>" );
将计数器列的最后一个元素更改为新数字,但 ':last' 选择器在这种情况下似乎不起作用。这是我的代码供参考(对不起我的表格丑陋。我试图让它看起来尽可能漂亮,但由于我的经验有限,它看起来仍然像是在出生时被打错了):
<html>
<head>
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script src="jquery.maskedinput.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#btnAdd').click(function() {
var num = $('.ccinput').length; // how many "duplicatable" input fields we currently have
var newNum = new Number(num + 1); // the numeric ID of the new input field being added
// create the new element via clone(), and manipulate it's ID using newNum value
var newElem = $('#input' + num).clone().attr('id', 'input' + newNum);
// insert the new element after the last "duplicatable" input field
$('#input' + num).after(newElem);
$("#rowcount").replaceWith( "<td>" + newNum + "</td>" );
// enable the "remove" button
$('#btnDel').attr('disabled','');
$("*#date").mask("99/99/9999");
// business rule: you can only add 20 names
if (newNum == 20)
$('#btnAdd').attr('disabled','disabled');
});
$('#btnDel').click(function() {
var num = $('.ccinput').length; // how many "duplicatable" input fields we currently have
$('#input' + num).remove(); // remove the last element
// enable the "add" button
$('#btnAdd').attr('disabled','');
// if only one element remains, disable the "remove" button
if (num-1 == 1)
$('#btnDel').attr('disabled','disabled');
});
$("*#date").mask("99/99/9999");
});
</script>
</head>
<body>
<form method="post" action="<?php echo htmlentities($PHP_SELF); ?>">
<table border="1" cellspacing="0">
<tr>
<th></th>
<th># (last four digits)</th>
<th>Amount</th>
<th>Approval</th>
<th>Date Received</th>
</tr>
<tbody>
<tr id="input1" class="ccinput">
<td id="rowcount"> 1 </td>
<td> <input id="cnum" type="text" name="cc_num[]" maxlength="4" /> </td>
<td> <input id="camnt" type="int" name="cc_amnt[]" /> </td>
<td> <input id="appr" type="text" name="cc_app[]" maxlength="10" /> </td>
<td> <input id="date" type="text" name="cc_date[]" /> </td>
</tr>
</tbody>
</table>
<div>
<input type="button" id="btnAdd" value="Add" />
<input type="button" id="btnDel" value="Remove" />
</div>
<input type="submit" value="Submit" name="submit" />
</form>
</body>
</html>