我有一个包含行和input
/select
表单元素的表格。在底行,我有一个按钮可以将新行添加到表中。最初,表格是空的,只有一行带有按钮
像这样:
<form name="test" id="test" action="#" >
<table id="matrix">
<tr id="1">
<td><select class="parent" name="parent">
<option value="C" label="C">C</option>
<option selected="selected" value="P" label="P">P</option>
<option value="B" label="B">B</option>
</select></td>
<td><div id="my_data_1">
<span title="parent_val"></span>
</div></td>
<td> </td>
</tr>
<tr >
<td colspan="3"><input type="button" class="add_new" /></td>
</tr>
</table>
</form>
现在,当我单击带有 add_new
类的按钮时,我克隆第一行,增加其 id,然后将其插入到最后一行上方。
问题是我有一个 onchange 事件附加到选择,父类为
$('#matrix').on('change', 'select.parent_type', function() {
var RowID = $(this).closest('tr').attr('id');
var attributes_div = $('#matrix tr#'+RowID).find('div#my_data'+RowID );
new_id = GetParentIDFormat(attributes_div, 3);
$(attributes_div +"span[title='parent_val']").html(new_id);
});
当我添加两行或更多行时,更改函数会更改所有行的 SPAN“parent_val”值,而不是更改 SELECT 父级的特定行。
最佳答案
存在一些错误,如果没有 GetParentIDFormat
函数,我无法提供 100% 的解决方案,但这里是:
'select.parent_type'
应为 'select.parent'
$('#matrix tr#'+RowID).find('div#my_data');
应该是
$('#' + RowID).find('.my_data');
.
请注意,您需要类,因为您不能拥有多个等效的 ID。
$(attributes_div +"span[title='parent_val']")
应该是
$("span[title='parent_val']", attribute_div)
结果:
$('#matrix').on('change', 'select.parent', function() {
var RowID = $(this).closest('tr').attr('id');
var attributes_div = $('#' + RowID).find('.my_data');
var new_id = GetParentIDFormat(attributes_div, 3);
$("span[title='parent_val']", attributes_div).html(new_id);
});
关于javascript - JQuery 克隆和 Onchange 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19813825/