我一直在尝试使用JQuery。我有以下功能:更新下一个同步元素
<script type="text/javascript">
$(function(){
// start a counter for new row IDs
// by setting it to the number
// of existing rows
var newRowNum = 2;
// bind a click event to the "Add" link
$('#addnew').click(function(){
// increment the counter
newRowNum += 1;
// get the entire "Add" row --
// "this" refers to the clicked element
// and "parent" moves the selection up
// to the parent node in the DOM
var addRow = $(this).parent().parent();
// copy the entire row from the DOM
// with "clone"
var newRow = addRow.clone();
// set the values of the inputs
// in the "Add" row to empty strings
//$('input', addRow).val('');
//$('name', addRow).val('os' + newRowNum);
// replace the HTML for the "Add" link
// with the new row number
$('td:first-child', newRow).html('<input type="hidden" name="on' + newRowNum + '" value="Email Address ' + (newRowNum - 1) + '">Recipient');
// insert a remove link in the last cell
$('td:last-child', newRow).html('<a href="" class="remove">Remove<\/a>');
// loop through the inputs in the new row
// and update the ID and name attributes
$('td:first-child.next-child.input', newRow).each(function(i){
var newID = newRowNum;
$(this).attr('id','os' + newID).attr('name','os' + newID);
});
//$('td:first-child.next', newRow).html('<input type="text" id="os' + newRowNum + '" name="os' + newRowNum + '" value="">');
// insert the new row into the table
// "before" the Add row
addRow.before(newRow);
// add the remove function to the new row
$('a.remove', newRow).click(function(){
$(this).parent().parent().remove();
return false;
});
// prevent the default click
return false;
});
});
</script>
在HTML中,我有这样的(一个更大的代码块的一部分):
<tr>
<td><input type="hidden" name="on2" value="Email Address 1"><a id="addnew" href="">Add</a></td><td><input name="os2" type="text" id="os2" value="" size="24" maxlength="60" /></td>
<td> </td>
</tr>
什么是应该在这里发生的是,当添加链接点击,添加更改为带有名称=“on + newRowNum”的隐藏表单元素的收件人(对于添加的每个新行增加1),并且id相同。这工作得很好。然而,在接下来的第二部分中,我需要更新文本输入的名称和id以匹配newRowNum,在这种情况下,name =“os + newRowNum”等。我无法做到这一点。我很可能不会使用适当的表单来访问它。我试过以下所有内容:
$('td:first-child.next-child.input', newRow).each(function(i){
var newID = newRowNum;
$(this).attr('id','os' + newID).attr('name','os' + newID);
});
$('td:firstChild.nextSibling.input', newRow).each(function(i){
var newID = newRowNum;
$(this).attr('id','os' + newID).attr('name','os' + newID);
});
加上上面的许多其他版本。任何人都可以帮我解决这个问题吗?希望这不是太模糊。
对,但我在这一行有两个输入元素,所以这不会让它们都具有相同的名称和ID?我需要第一个(隐藏的元素)的名称和ID为on + newRowNum,第二个名称和ID为os + newRowNum。 Dave – Dave 2009-10-14 21:33:29
我的不好,现在会修改:) – 2009-10-14 21:36:39
也修改了代码和演示。看看使用Firebug或其他DOM检查器的'name'和'id'属性 – 2009-10-14 21:39:56