我有一個通過添加/刪除行(表單輸入)通過JS動態更改的表格/表格。我想創建一個計算行數列,所以我嘗試使用,jQuery - 選擇具有相同ID的組的最後一個元素
$("#rowcount:last").replaceWith("<td>" + newNum + "</td>");
到最後一個元素改變計數器列到新的號碼,但「:最後一個」選擇似乎不工作在這種情況下。這裏是我的代碼供參考(對於我的表單的醜陋抱歉,我試圖讓它看起來儘可能漂亮,但由於我有限的經驗,它仍然看起來像在出生時被打在了錯誤的一邊):
<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>
':))'如果你的DOM中有相同的多個'id',你的HTML就會失效, – 2012-08-07 22:13:20
這是什麼'$(「*#date」)'? – elclanrs 2012-08-07 22:14:17
對於多個ID,HTML似乎運行良好,唯一的問題是我只能選擇第一個ID或全部元素,而不是最後一個ID。我不知道爲什麼會發生這種情況。同樣,這實際上是我用HTML/JS編寫的第一件事,所以我的知識非常有限。 $(「*#date」)使用jQuery的屏蔽輸入插件將所有日期輸入掩蓋爲99/99/9999格式。 – user1562781 2012-08-07 22:22:09