我正在创建一个新行,例如
var newRow = $(this).closest('tr').clone().appendTo('#gridInAnswers').find('input').val('');
现在我想更改输入元素的 id。如何做到这一点?我正在考虑
var i = gridInAnsLength;
$('input', newRow).each(function() {
$(this)[0].id = "Col" + counter + "_" + (i++)
});
但它不起作用。请提出建议。
我的 html 模型就像
<head>
<script type="text/javascript" src="jquery-1.4.2.min.js">
</script>
<style type="text/css">
div{ padding:4px; }
</style>
</head>
<body>
<script type="text/javascript">
$(document).ready(
function() {
var counter = 2;
$('a.add').live('click', function() {
if (counter > 5) {
alert("Only 5 textboxes allowed");
return false;
}
var newRow =
$(this).closest('tr').clone().appendTo('#gridInAnswers').find('input').val('');
var i = 2;
$('input', newRow).each(function() {
$(this).attr("id", "Col"+ (i++));
});
$(this).text('Remove').removeClass('add').addClass('remove');
counter++;
});
$('a.remove').live('click', function() {
$(this).closest('tr').remove();
counter--;
});
$("#getButtonValue").click(function() {
var gridInAnswerValuesHtml = "";
$(".grdAns").each(function() {
//ansString += this.value+",";
gridInAnswerValuesHtml += "<input type = \"hidden\" name = \"gridInAnswers\" value = \"";
gridInAnswerValuesHtml += this.value;
gridInAnswerValuesHtml += "\">";
});
alert(gridInAnswerValuesHtml);
});
});
</script>
</head>
<body>
<table id="gridInAnswers">
<tr>
<th>
Min Value
</th>
<th>
Max Value
</th>
</tr>
<tr>
<td>
<input type="text" name="col1" id="Col1_2" class="grdAns" />
</td>
<td>
<input type="text" name="col1" id="Col1_3" class="grdAns" />
</td>
<td>
<a href="#" class="add">Add</a>
</td>
</tr>
<tr>
<input type='button' value='Get TextBox Value' id='getButtonValue'>
</tr>
</table>
</body>
最佳答案
关于Jquery改变子元素的id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4384830/