关注此问题 - Extending Clone Table Rows functionality - changing row ID
代码 - http://jsfiddle.net/EwQUW/58/
我想更新attr。请检查代码,我附上评论,看看我在说什么。
修改
<table id="table">
<tbody>
<tr>
<td>
<select name="make[]" id="make" onchange="change(this,'model')">
<option value="" selected=“selected”> Please Select </option>
<option value=Ford> Ford</option>
<option value=Nissan> Nissan</option>
<option value=Volvo> Volvo</option>
<option value=BMW> BMW</option>
</select>
</td>
<td>
<select name="model[]" id="model" onchange="change(this,'make')">
<option value="" selected=“selected”> Please Select </option>
<option value=Ford> Fiesta</option>
<option value=Nissan> Mirca</option>
<option value=Volvo> s60</option>
<option value=BMW> M3</option>
</select>
</td>
<td>
<input id="country" name="country[]"/>
</td>
<td>
<input id="city" name="city[]" />
</td>
</tr>
</tbody>
</table>
<button id="add">Add</button>
的Javascript
function change(fld,id) {
var opt = fld.selectedIndex;
if (fld[opt].value != ' ') {
var sel = document.getElementById(id);
for (var i = sel.options.length -1; i > -1; i--) {
if (fld[opt].value == sel[i].value) sel[i].selected = true;
}
}
}
当我添加一个新行时,我希望ID,NAME和onchange更新为您放置的计数或长度。
随着ID的更新和onchange到id = make到id = make2,所以onchange仍然有效
再次编辑
实际上名称将是一个数组。因此,只有IDS和Onchange需要根据行数进行更新
答案 0 :(得分:0)
我想出的第一个方法是:
function change(fld, id) {
var opt = fld.selectedIndex;
if (fld[opt].value != ' ') {
var sel = document.getElementById(id);
for (var i = sel.options.length - 1; i > -1; i--) {
if (fld[opt].value == sel[i].value) sel[i].selected = true;
}
}
}
$('select').change( // moving away from intrusive in-line JavaScript
function() {
var changeTarget; // used to determine which select to change
if (this.id == 'make') {
changeTarget = 'model';
}
else {
changeTarget = 'make';
}
change(this,changeTarget);
});
$('#add').click(
function() {
$('#table tbody tr:last').clone(true).appendTo($('#table')).find('input,select').each(
function() {
var attr = this.id.replace(/\d/, ''); // gets the text of the id attribute
var length = $('#table tbody tr').length; // finds what number the new attributes should be
if ($(this).is('input')){ // select elements don't need their name to be changed
$(this).attr({
'id': attr + length,
'name': attr + length
});
}
else if ($(this).is('select')){
$(this).attr('id',attr + length);
}
});
});
已编辑,将select
change()
事件处理程序中的硬编码'make'/'model'选项删除为以下内容:
$('select').change(
function() {
var changeTarget = $(this)
.closest('tr')
.find($('select'))
.not($(this))
.attr('id');
change(this,changeTarget);
});