我正在尝试将此演示中的“输入”更改为“选择”。该演示工作正常,即:
http://devblog.jasonhuck.com/assets/infiniteformrows.html
修改的问题是每次点击添加新行时,它都会丢失上一行选择,选择了什么。
<html>
<head>
<title>Infinite Form Rows</title>
<script
type="text/javascript"
src="http://cachefile.net/scripts/jquery/1.2.3/jquery-1.2.3.min.js">
</script>
<script type="text/javascript">
$(function(){
// start a counter for new row IDs
// by setting it to the number
// of existing rows
var newRowNum = 0;
// 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('');
$('select', addRow).val('');
// replace the HTML for the "Add" link
// with the new row number
$('td:first-child', newRow).html(newRowNum);
// 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
$('input', newRow).each(function(i){
var newID = newRowNum + '_' + i;
$(this).attr('id',newID).attr('name',newID);
});
// loop through the inputs in the new row
// and update the ID and name attributes
$('select', newRow).each(function(i){
var newID = newRowNum + '_' + i;
$(this).attr('id',newID).attr('name',newID);
});
// 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>
</head>
<body>
<form>
<table id="tabdata">
<thead>
<tr>
<th>Row</th>
<th>Cell 1</th>
<th>Cell 2</th>
<th>Cell 3</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td><a id="addnew" href="">Add</a></td>
<td> <select name="1_0" id="1_0" style="width: 160px;">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3">Option 3</option>
<option value="option4">Option 4</option>
<option value="option5">Option 5</option>
</select>
</td>
<td><input id="n0_2" name="n0_2" type="text" /></td>
<td><input id="n0_3" name="n0_3" type="text" /></td>
<td></td>
</tr>
</tbody>
</table>
<input id="go" name="go" type="submit" value=" Save " />
</form>
</body>
</html>
答案 0 :(得分:0)
在所有输入上添加焦点事件以设置currentFocus。
var currentFocus = null;
$(':input').focus(function(){currentFocus = $(this))})
然后在$('#addnew')中。点击,将其添加到底部
if (currentFocus)
currentFocus.focus();